在下面的示例代码中,我在失败时调用complete(false)
。但是,由于我使用DispatchGroup
对象来确保所有异步请求都完成,所以不能只在失败时调用syncGroup.leave()
,因为notify
将被调用,其中包含complete(true)
,使该函数返回true
,而它应该返回失败的false
。
在未能正确完成我的功能时,我没有调用syncGroup.leave()
,对吗?或者我应该打电话给syncGroup.leave()
,并以某种方式确定结果是什么,这样我就可以在失败时返回false
。
let syncGroup = DispatchGroup()
syncGroup.enter()
for track in unsynced {
register(time: time, withCompletion: { (success: Bool) -> () in
if success {
self.debug.log(tag: "SyncController", content: "Registered")
syncGroup.leave()
}
else {
complete(false)
}
})
}
//all requests complete
syncGroup.notify(queue: .main) {
self.debug.log(tag: "SyncController", content: "Finished registering")
complete(true)
}
发布于 2016-11-17 11:21:55
您必须在for循环中输入组。您可能需要引入一个额外的错误标志。
实例实现:
var fail = false
let syncGroup = DispatchGroup()
for track in unsynced {
syncGroup.enter()
register(time: time, withCompletion: { (success: Bool) -> () in
if success {
self.debug.log(tag: "SyncController", content: "Registered")
syncGroup.leave()
}
else {
fail = true
syncGroup.leave()
}
})
}
//all requests complete
syncGroup.notify(queue: .main) {
if fail {
complete(false)
} else {
self.debug.log(tag: "SyncController", content: "Finished registering")
complete(true)
}
}
https://stackoverflow.com/questions/40652869
复制相似问题