ios - 如何同步闭包?

标签 ios swift swift3

如何同步闭包?

我有这个代码:

    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?()

    }

在我的代码中,completion?() 会调用,而不是在所有请求结束时调用 当所有请求结束时,我需要调用完成?()。我可以吗?

最佳答案

由于当前接受的答案不正确,这里有一个正确使用 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?()
    }
}

关于ios - 如何同步闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43146356/

相关文章:

ios - Swift:无法将类型 'Item?' 的值分配给类型 'Item?.Type'

swift - 无法使用采样器显示纹理

swift - 无法下载使用 AVFoundation 的 apple-music

ios - MPMusicPlayer 错误域=MPErrorDomain 代码=4?

ios - 从 Swift 中的 documentDirectory 中删除所有文件

ios - 我必须使用正则表达式来提取消息还是有属性?

arrays - 快速删除数组范围内的对象

ios - 使用swift 3发送post请求(自签名证书问题)

ios - 在 Swift 3 中获取 Google Drive iOS 基本目录中的文件夹列表?

ios - Google Places API 警告