我正在尝试在for循环中使用完成处理程序。问题是它将在完成处理程序返回之前继续运行循环,因为它是异步调用。附上是我的代码。我需要使用GCD吗?我(很明显)是swift / ios的新人。任何建议将不胜感激。鲍勃
for srcTerm in sFields { //search using all search fields
multiQuery (searchTerm: srcTerm) {
if srResult.count < self.lastValue {
self.lastValue = srResult.count
self.lastSearch = srcTerm
}
}
// Do more stuff
}
func multiQuery (searchTerm: String, completion: @escaping ([PFObject]) -> ()) {
var exArray = [PFObject] ()
let query = PFQuery(className: "searchLinks")
do {
query.whereKey("searchTerms", equalTo: searchTerm)
query.findObjectsInBackground (block: { (objects, error)-> Void in
if let error = error {
print("Error Generated: ",error)
return
}
if let objects = objects {
// do stuff
}
completion(self.srResult)
})
}
} // end of function
答案 0 :(得分:2)
您可以使用DispatchGroups,这是一个示例(取自https://medium.com/@wilson.balderrama/how-to-use-dispatchgroup-gdc-with-swift-3-35455b9c27e7。类似于GCD with nested Parse Queries但更新为Swift 3 API):
// Just a sample function to simulate async calls
func run(after seconds: Int, closure: @escaping () -> Void) {
let queue = DispatchQueue.global(qos: .background)
queue.asyncAfter(deadline: .now() + .seconds(seconds)) {
closure()
}
}
let group = DispatchGroup()
group.enter()
run(after: 6) {
print("Hello after 6 seconds")
group.leave()
}
group.enter()
run(after: 3) {
print("Hello after 3 seconds")
group.leave()
}
group.enter()
run(after: 1) {
print("Hello after 1 second")
group.leave()
}
group.notify(queue: DispatchQueue.global(qos: .background)) {
print("All async calls were run!")
}
使用您的代码:
let group = DispatchGroup()
for srcTerm in sFields { //search using all search fields
group.enter()
multiQuery (searchTerm: srcTerm) {
if srResult.count < self.lastValue {
self.lastValue = srResult.count
self.lastSearch = srcTerm
}
group.leave()
}
}
group.notify(queue: DispatchQueue.global(qos: .background)) {
// Do something after all async calls are done
}