创建和恢复NSURLSessionTask后,为什么NSURLSession
操作队列为空?
有没有办法判断NSURLSession是否有待处理的任务?
目标是等待多个任务完成,但这不起作用:
NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithStreamedRequest:request];
[uploadTask resume];
// this prints "0"
NSLog(self.session.delegateQueue.operationCount)
// this returns immediately instead of waiting for task to complete
[self.session.delegateQueue waitUntilAllOperationsAreFinished];
答案 0 :(得分:5)
我找到了一种解决方案,可以使用建议的DispatchGroup
(答案在Swift中,而问题在于ObjC ......但它是相同的逻辑)
请注意,在使用uploadTaskWithStreamedRequest:
时,我们需要实施URLSessionTaskDelegate
和func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
。因此,为了简化答案,我将演示DispatchGroup
与uploadTaskWithRequest:from:completionHandler:
的使用。
// strong reference to the dispatch group
let dispatchGroup = DispatchGroup()
func performManyThings() {
for _ in 1...3 {
let request = URLRequest(url: URL(string: "http://example.com")!)
dispatchGroup.enter()
let uploadTask = self.session.uploadTask(with: request, from: nil) { [weak self] _, _, _ in
self?.dispatchGroup.leave()
}
uploadTask.resume()
}
dispatchGroup.notify(queue: .main) {
// here, all the tasks are completed
}
}