Allow the user to resume a download without starting over.
Your app or the user may need to cancel an in-progress download and resume it later. By supporting resumable downloads, you save both the user’s time and network bandwidth.
You can also use this technique to resume a download that fails due to a temporary loss of connectivity.
Store the Resume Data Object When You Cancel the Download
You cancel a
NSURLSession by calling
cancel. This method takes a completion handler which is called once the cancellation is complete. The completion handler receives a
resume parameter. If it it not
nil, this is the token you use later to resume the download. Listing 1 shows how to cancel a download task and store
resume, if it exists, in a property.
Store the Resume Data Object When a Download Fails
You can also resume a download that has failed due to a temporary loss of connectivity, as when the user walks out of WiFi range.
When the download fails, the session calls your
URLSession: delegate method. If
error is not
nil, look in its
user dictionary for the key
NSURLSession. If the key exists, save the value associated with it to use later when you try to resume the download. If the key does not exist, the download can’t be resumed.
Listing 2 shows an implementation of
URLSession: that retrieves and saves the
resume object, if any, from the error.
Use the Stored Resume Data Object to Resume Downloading
When it’s appropriate to resume the download, create a new
NSURLSession by using the
download method of
NSURLSession, passing in the
resume object you stored earlier. Then call
resume on the task to resume the download.
If the download resumes successfully, the task calls your delegate’s
URLSession: method. You can use the offset and byte count parameters to inform the user that the download has resumed and has preserved its earlier progress.