我想知道在for循环中处理异步调用的最佳方法是什么,所以我们知道上次调用的结束时间。
这里的问题是for循环比服务器调用快,所以调用将排队,我如何确保最后一次 制作并结束了?
采用以下伪示例:
someData.forEach({(object) in
self.myFunc(object)
})
fileprivate func myFunc(object: object) {
doesSomeServerAsyncCallWithObjectAndCompletion(object) {(success, desiredData) in
// HOW TO KNOW HERE THAT THIS WAS THE LAST CALL REQUESTED??
}
}
答案 0 :(得分:2)
使用DispatchGroup
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
longRunningFunction { dispatchGroup.leave() }
dispatchGroup.enter()
longRunningFunctionTwo { dispatchGroup.leave() }
dispatchGroup.notify(queue: .main) {
print("Both functions complete ")
}
例如
let queue = DispatchQueue(label: "com.allaboutswift.dispatchgroup", attributes: .concurrent, target: .global())
let group = DispatchGroup()
group.enter()
queue.async (group: group) {
print("doing stuff again 1")
group.leave()
}
group.enter()
queue.async (group: group) {
print("doing more stuff again 2 ")
sleep(3)
group.leave()
}
group.notify(queue: DispatchQueue.main) {
print("done doing stuff again 3")
}