我尝试使用 NSURLSessionDataTask
下载 zip 存档。
我知道有一个 NSURLSessionDownloadTask
,但重点是我想要一个 didReceiveData
回调(以显示进度)。
代码是:
NSURLRequest *request = [NSURLRequest requestWithURL:@"..."
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSOperationQueue *myQueue = [NSOperationQueue new];
myQueue.underlyingQueue = dispatch_get_main_queue();
NSURLSession *session = [NSURLSession sessionWithConfiguration:config
delegate:self
delegateQueue:myQueue];
NSURLSessionDataTask* task = [session dataTaskWithRequest:request
completionHandler:^( NSData *data, NSURLResponse *response, NSError *error){ ... }
[task resume];
我的类符合 NSURLSessionDataDelegate
。
当我调用该方法时,几秒钟后调试器会转到带有 nil
数据和 nil
错误的completionHandler。
我做错了什么?
我也尝试过:
- 在没有completionHandler的情况下调用,然后调试器转到带有200响应的
didReceiveResponse
回调,仅此而已。 - 使用
[NSOperationQueue new]
作为队列 - 使用
[NSURLSession sharedSession]
- 没有得到任何响应 - 使用
[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier: @"..."]
- 说我不能使用 completionHandler,但没有它 - 也没有响应。
最佳答案
所以我找到了答案,但从文档中看并不是很明显:
我有几个回调,其中有 didReceiveResponse
.
事实证明,我必须调用完成处理程序,以便将来的回调工作,即:
completionHandler(NSURLSessionResponseAllow);
还有一件事:didCompleteWithError
实际上也是告诉成功完成的委托(delegate),尽管名称暗示这是错误处理程序。
含义:下载成功完成后,调用此函数并返回错误 = nil
。
希望有一天这会对某人有用。
关于ios - NSURLSession 不返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51061130/