如何等待 NSURLSession 的所有任务完成? [英] How to wait for all tasks of an NSURLSession to complete?

查看:90
本文介绍了如何等待 NSURLSession 的所有任务完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么NSURLSession操作队列在创建并恢复NSURLSessionTask后为空?

Why is NSURLSession operation queue empty after creating and resuming an NSURLSessionTask?

有没有办法判断一个 NSURLSession 是否有待处理的任务?

Is there a way to tell if an NSURLSession has tasks pending?

目标是等待多个任务完成,但这不起作用:

The goal is to wait for multiple tasks to complete, but this doesn't work:

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 避免使会话无效.

I found a solution that avoids invalidating the session, using the suggested DispatchGroup.

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

(answer is in Swift, while question is in ObjC ... but it's the same logic)

注意,在使用时,uploadTaskWithStreamedRequest:,我们需要实现一个URLSessionTaskDelegatefunc urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError 错误:错误?).因此,为了简化答案,我将演示 DispatchGroupuploadTaskWithRequest:from:completionHandler: 的使用.

Note that when using, uploadTaskWithStreamedRequest:, we need to implement an URLSessionTaskDelegate and func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?). So, to simplify the answer, I will demonstrate the use of 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
    }
}

这篇关于如何等待 NSURLSession 的所有任务完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆