简体   繁体   English

如何同步闭包?

[英]How can I synchronize closures?

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? 我可以这样做吗?

Since the currently accepted answer isn't correct, here is a version that properly uses a DispatchGroup . 由于当前接受的答案不正确,因此这是一个正确使用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?()
    }
}

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?() . 当您预期的所有请求都已结束时,您调用completion?()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何同步多个SKSpriteNodes的动画? - How can I synchronize the animation of multiple SKSpriteNodes? 如何录制视频并将其与 AVPlayer 同步? - How can I record a video and synchronize it with an AVPlayer? 当我的应用程序处于后台时,如何与云同步项目? - How can I synchronize items with the cloud while my app is in the background? 我如何在firebase .ref闭包内部访问变量并在外部使用它们 - How can i access variables inside of firebase .ref closures and use them outside 使用C#和Xamarin表单-如何在不设置闭包链的情况下关闭一个模式 - Using C# & Xamarin Forms - How can I close one modal without setting of chain of closures “NSUserDefaults 同步”怎么能跑得这么快? - How can `NSUserDefaults synchronize` runs so fast? 如何使用iCloud在我的应用程序之间同步.zip文件? - How can I use iCloud to synchronize a .zip file between my apps? 如何在Swift中同步对我的Web服务的调用并在地图上显示数据(带有标记聚类)? - how can I synchronize a call to my webservice and displaying the data on the map (with marker clustering) in Swift? 如何同步添加新的CALayer对象和另一个对象的动画 - How can I synchronize adding a new CALayer object with animations of another object 如何使用iCloud在我的应用程序之间同步UIdocument文件(保存在本地文档目录中)? - How can I use iCloud to synchronize a UIdocument files (saved in local document directory) between my apps?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM