2

How can I synchronize closures?

I have this code:

    private func getWeather(parameters: [String : Any],  failure: ((String) -> Void)? = nil ,completion: (() -> Void)? = nil) {

        for _ in 0...10 {

            RequestManager.sharedInstance.request(url: baseURL, parameters: parameters, completion:  { (result) in
                if JSON.parse(result)["name"].string == nil {
                    failure?("Something went wrong. Please, try again later")
                } else {
                    let weatherModel: WeatherModel = WeatherModel(json: JSON.parse(result))
                }
            })
        }
        completion?()

    }

In my code, completion?() will call, not when all requests will ended And I need call completion?() when all requests will ended. Ho can I do it?

4
  • 2
    Research DispatchGroup.
    – rmaddy
    Commented Mar 31, 2017 at 17:20
  • 1
    Here is a great tutorial Commented Mar 31, 2017 at 17:21
  • Or have a look on nsoperation(queue) and setup dependencies Commented Mar 31, 2017 at 17:39
  • @vikingosegundo The problem with trying to use dependent operations in this case is that the operations kick off their own async operation.
    – rmaddy
    Commented Mar 31, 2017 at 18:06

2 Answers 2

10

Since the currently accepted answer isn't correct, here is a version that properly uses a DispatchGroup.

private func getWeather(parameters: [String : Any],  failure: ((String) -> Void)? = nil ,completion: (() -> Void)? = nil) {
    let dispatchGroup = DispatchGroup()
    for _ in 0...10 {
        dispatchGroup.enter()
        RequestManager.sharedInstance.request(url: baseURL, parameters: parameters) { result in
            if JSON.parse(result)["name"].string == nil {
                failure?("Something went wrong. Please, try again later")
            } else {
                let weatherModel: WeatherModel = WeatherModel(json: JSON.parse(result))
            }
            dispatchGroup.leave()
        }
    }

    dispatchGroup.notify(queue: DispatchQueue.main) {
        completion?()
    }
}
3
  • Thank you. I will start using this, and delete my accepted answer... or I can't delete an accepted answer...
    – Sethmr
    Commented Mar 31, 2017 at 18:03
  • Oh, @rmaddy, Thank you so much for your help!
    – Banck
    Commented Mar 31, 2017 at 18:17
  • @rmaddy I made a meta post about the scenario if you want to contribute. meta.stackoverflow.com/questions/346284/…
    – Sethmr
    Commented Mar 31, 2017 at 18:22
0

An easy way to do this is just to count completed calls.

private func getWeather(parameters: [String : Any],  failure: ((String) -> Void)? = nil ,completion: (() -> Void)? = nil) {
    let numCalls = 11;
    var completedCalls = 0;

    for _ in 0..<numCalls {

        RequestManager.sharedInstance.request(url: baseURL, parameters: parameters, completion:  { (result) in
            if JSON.parse(result)["name"].string == nil {
                failure?("Something went wrong. Please, try again later")
            } else {
                let weatherModel: WeatherModel = WeatherModel(json: JSON.parse(result))
            }
            completedCalls += 1
            if completedCalls == numCalls {
                completion?()
            }
        })
    }
}

Your completion callback runs when each request ends. Making each of your completion callbacks update a value in its enclosing scope allows you to keep track of how many requests have ended. When all the requests you expect have ended, you call completion?().

3
  • yeah, It is obvious)) But I think that there is some elegant solution :-)
    – Banck
    Commented Mar 31, 2017 at 17:27
  • You could try creating a function which abstracts this call-counting pattern. It would take which request to make and how many times to make it, or a list of requests. Commented Mar 31, 2017 at 17:33
  • I would definitely recommend using DispatchGroup over this.
    – Sethmr
    Commented Mar 31, 2017 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.