gpt4 book ai didi

ios - 如何同步闭包?

转载 作者:可可西里 更新时间:2023-10-31 23:58:46 26 4
gpt4 key购买 nike

如何同步闭包?

我有这个代码:

    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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com