我有以下代码:
func testFunc(completion: (Bool) -> Void) {
let queue = NSOperationQueue()
queue.maxConcurrentOperationCount = 1
for i in 1...3 {
queue.addOperationWithBlock{
Alamofire.request(.GET, "https://httpbin.org/get").responseJSON { response in
switch (response.result){
case .Failure:
print("error")
break;
case .Success:
print("i = \(i)")
}
}
}
//queue.addOperationAfterLast(operation)
}
queue.waitUntilAllOperationsAreFinished()
print("finished")
}
输出为:
finished
i = 3
i = 1
i = 2
但我期望以下几点:
i = 3
i = 1
i = 2
finished
那么,为什么queue.waitUntilAllOperationsAreFinished()不要等待?
最佳答案
您添加到队列中的每个操作都会立即执行,因为Alamofire.request
只是返回而无需等待响应数据。
此外,那里可能出现死锁。由于responseJSON
块默认情况下在主队列中执行,因此通过调用waitUntilAllOperationsAreFinished
阻塞主线程将完全阻止其执行完成块。
首先,为了解决死锁问题,您可以告诉Alamofire在另一个队列中执行完成块,其次,可以使用dispatch_group_t
对异步HTTP请求的数量进行分组,并使主线程一直等待,直到所有这些请求都在队列中。小组完成执行:
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
let group = dispatch_group_create()
for i in 1...3 {
dispatch_group_enter(group)
Alamofire.request(.GET, "https://httpbin.org/get").responseJSON(queue: queue, options: .AllowFragments) { response in
print(i)
dispatch_async(dispatch_get_main_queue()) {
// Main thread is still blocked. You can update the UI here but it will take effect after all HTTP requests are finished.
}
dispatch_group_leave(group)
}
}
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
print("finished")