NSURLSessionDownloadTask failed

At first, I thought that if the NSURLSessionDownloadTask method successfully completes the URLSession:downloadTask:didFinishDownloadingToURL: call will be called if for some reason it does not work - URLSession:task:didCompleteWithError: It works as expected on the simulator (only one of these methods is called for one download task), but on the device it is not: in case of failure both of these methods are called, URLSession:downloadTask:didFinishDownloadingToURL: is the first. (both of these methods pass the same task in parameters)

Is there something I am missing?

+6
source share
4 answers

Use completion block instead of delegation:

 NSURLSessionDownloadTask *mySessionDownloadTask = [myURLSession downloadTaskWithRequest:myRequest completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) { dispatch_async(dispatch_get_main_queue(), ^{ if(!error) { // Finish loading } else { // Handle error }); }]; 

Note. If you do not receive the main queue, any update related to the user interface will be delayed, which causes unexpected behavior.

+1
source

According to Apple documentation in the NSURLSessionDownloadDelegate section This is standard behavior.

 /* Sent when a download task that has completed a download. The delegate should * copy or move the file at the given location to a new location as it will be * removed when the delegate message returns. URLSession:task:didCompleteWithError: * will still be called. */ 
+1
source

I found a solution to this problem:

To get the status code in the response header, you must first run NSURLSessionDataTask .

This will call the following delegate method of URLSession: dataTask: didReceiveResponse: completeHandler:.

In this method, you can first check the status code of the NSURLResponse parameters (dropping it to NSHTTPURLResponse) and finally call the completion handler using NSURLSessionResponseBecomeDownload to convert your dataTask to downloadTask (which will behave the way you would expect from NSURLSessionDownloadTaskRancelance) to avoid loading some data that you do not need (for example, if the response status code is 404).

In addition, if you need to do something with the converted NSURLSessionDownloadTask (for example, save it in an array or dictionary or replace the data task with a new object), this can be done in URLSession: dataTask: didBecomeDownloadTask:

Hope this helps someone!

0
source

NSURLSessionDownloadTask is a subclass of NSURLSessionTask that has the error property. Could you check this in your delegate method URLSession:downloadTask:didFinishDownloadingToURL: before trying to copy the file?

-1
source

All Articles