Why is NSURLSession
创建并恢复 NSURLSessionTask 后操作队列为空?
有没有办法判断 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];
我找到了一个解决方案,使用建议的方法避免使会话无效DispatchGroup
.
(答案在 Swift 中,而问题在 ObjC 中......但逻辑相同)
使用时请注意,uploadTaskWithStreamedRequest:
,我们需要实施一个URLSessionTaskDelegate
and func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
。因此,为了简化答案,我将演示如何使用DispatchGroup
with 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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)