如何等待NSURLSession的所有任务完成?

时间:2016-11-30 07:57:14

标签: ios nsurlsession nsoperationqueue nsurlsessiontask

创建和恢复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];

1 个答案:

答案 0 :(得分:5)

我找到了一种解决方案,可以使用建议的DispatchGroup

来避免会话无效

(答案在Swift中,而问题在于ObjC ......但它是相同的逻辑)

请注意,在使用uploadTaskWithStreamedRequest:时,我们需要实施URLSessionTaskDelegatefunc urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)。因此,为了简化答案,我将演示DispatchGroupuploadTaskWithRequest: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
    }
}