UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Dispatch.group().wait() don't work inside a function

Forums > Swift

I have a function where I put network task into dispatch group, and then use .wait() to not return value until this task will finish but it don't work. Does anyone have suggestions how to fix this? Thanks in advance!

class PunkApiService{

    var beers = [Beer]()

    func loadList(at page: Int){
        //MARK: - Checks is URL is valid + pagination
        guard let url = URL(string: "https://api.punkapi.com/v2/beers?page=\(page)&per_page=25") else {
            print("Invalid URL")
            return
        }
        //MARK: - Creating URLSession DataTask
        let task = URLSession.shared.dataTask(with: url){ data, response, error in
            //MARK: - Handling no erros came
            guard error == nil else {
                print(error!)
                return
            }
            //MARK: - Handling data came
            guard let data = data else{
                print("Failed to load data")
                return
            }
            do{
                let beers = try JSONDecoder().decode([Beer].self, from: data)
                self.beers.append(contentsOf: beers)
            }
            catch{
                print("Failed to decode data")
            }
        }
        task.resume()
    }
}
class BeersListInteractor:BeersListInteractorProtocol{
    private var favoriteBeers = FavoriteBeers()
    private var service  = PunkApiService()
    //MARK: - Load list of Beers
    func loadList(at page: Int) -> [Beer]{
        let group = DispatchGroup()
        group.enter()
        DispatchQueue.global().sync{
        self.service.loadList(at: page)
        group.leave()
        }
        group.wait()
        return service.beers

    }

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.