如何同步闭包?
我有这段代码:
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?()
}
在我的代码中,完成?()将调用,而不是所有请求都将结束 当所有请求都结束时,我需要调用完成?()。我可以这样做吗?
答案 0 :(得分:8)
由于当前接受的答案不正确,因此这是一个正确使用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?()
}
}
答案 1 :(得分:0)
一种简单的方法就是计算已完成的电话。
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?()
}
})
}
}
每个请求结束时都会运行完成回调。使每个完成回调更新其封闭范围中的值允许您跟踪已结束的请求数。当您预期的所有请求都已结束时,请致电completion?()
。