How to resume NSURLSession download process after app force-quit and app relaunch?

Emil Adz picture Emil Adz · Aug 9, 2015 · Viewed 8.5k times · Source

I have implemented NSURLSession for downloading fairly large files from our servers. Now as long as I'm working in foreground or background and go back to the app the transactions are working and getting finished.

But if I force-quit the app using the the multitasking screen and re-open the app again. the downloading process is not getting finished although as I understood from the docs, it should, here what the docs state:

If an iOS app is terminated by the system and relaunched, the app can use the same identifier to create a new configuration object and session and retrieve the status of transfers that were in progress at the time of termination. This behavior applies only for normal termination of the app by the system. If the user terminates the app from the multitasking screen, the system cancels all of the session’s background transfers. In addition, the system does not automatically relaunch apps that were force quit by the user. The user must explicitly relaunch the app before transfers can begin again.

Meaning if I relaunch the app the transaction before the force-quit should started again, or are they? Is there an additional operation I need to commit in order this to work?

UPDATE: I stumbled on this project: https://github.com/Heikowi/HWIFileDownload#force-quit

That states:

Force Quit

After the app has been killed by the user, downloads do not continue in the background. On iOS 7 (and later) resume data is passed back.

Meaning there is a way to receive resume data even if the application was killed by the user in the background. Only the project is written in Objective-C and I can't understand what are they doing to achieve this.

Answer

Fabio Felici picture Fabio Felici · Oct 5, 2015

After a force-quit the:

 NSURLSessionTaskDelegate - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error

delegate method will be called when the app is restarted. If the download task can be resumed the error object will contain the resume data:

[error.userInfo objectForKey:NSURLSessionDownloadTaskResumeData].

Using this data you can resume the download process by creating a NSURLSessionDownloadTask with:

(NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData*)resumeData.

More info about that can be found in Life Cycle of a URL Session with Custom Delegates, step 13.