在下面的示例代码中,我调用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)
}
您必须在 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)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)