Ios 如何同步闭包?
如何同步闭包 我有以下代码:Ios 如何同步闭包?,ios,swift,swift3,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, parameter
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?()将调用,而不是在所有请求结束时调用
我需要呼叫完成?()当所有请求结束时。我能怎么做?一个简单的方法就是计算已完成的呼叫数
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?()
}
})
}
}
private func getWeather(参数:[String:Any],失败:((String)->Void)?=nil,完成:(()->Void)?=nil){
设numCalls=11;
var completedCalls=0;
对于0中的u0..由于当前接受的答案不正确,这里有一个正确使用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?()
}
}
研究调度组
。或查看NSO操作(队列)和设置dependencies@vikingosegundo在这种情况下,尝试使用依赖操作的问题是,这些操作启动了它们自己的异步操作。是的,这是显而易见的),但我认为有一个优雅的解决方案:-)您可以尝试创建一个函数来抽象这个调用计数模式。它将需要发出哪个请求我会推荐使用DispatchGroup而不是它。谢谢。我会开始使用它,并删除我接受的答案…或者我不能删除接受的答案…哦,@rmaddy,非常感谢你的帮助!@rmaddy如果你想贡献的话,我就发了一篇关于这个场景的元帖子。