[英]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.