NSURLSession 不返回数据



我尝试使用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

当我调用该方法时,几秒钟后调试器将转到 completionHandler,并显示nil数据和nil错误。 我做错了什么?

我也试过:

  • 调用没有完成处理程序,然后调试器转到具有 200 响应didReceiveResponse回调,仅此而已。
  • 对队列使用[NSOperationQueue new]
  • 使用[NSURLSession sharedSession]- 没有得到任何响应
  • 使用
  • [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier: @"..."]- 下降说我不能使用 completionHandler,但没有它 - 也没有响应。

所以我找到了答案,从文档中看不是很明显: 我有几个回调,其中didReceiveResponse.

事实证明,我必须调用完成处理程序才能使将来的回调起作用,即:completionHandler(NSURLSessionResponseAllow);

还有一件事:didCompleteWithError实际上是讲述成功完成的委托,尽管名称暗示这是错误处理程序。 含义: 下载成功完成后,将调用此函数,错误 =nil

希望有一天这对某人有用。

最新更新