You can have multiple NSURLSessionDownloadTask use the same NSSession and each are executed one after the other on the same mainQueue.
when successfully downloaded they call:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
If you download a MP4 of 100 mB and a pic of 10KB then they will return in different orders into this method.
So to track what session and what downloadTask has returned in this
you need to set a string identifier BEFORE you call the web service
To distinguish/track NSURLSessions you set
session.configuration.identifier
to distinguish NSURLSessionDownloadTask use
downloadTask_.taskDescription
downloadTask_.taskDescription = [NSString stringWithFormat:@"%@",urlSessionConfigurationBACKGROUND_.identifier];
For example in my project I was downloading a number of user favourite videos and their thumbnails.
Each item had a id e.g.1234567 So I needed to make two calls for each favourite
so i created two identifiers
"1234567_VIDEO"
"1234567_IMAGE"
then called two ws calls and passed in the identifier in session.configuration.identifier
http://my.site/getvideo/1234567
"1234567_VIDEO"
http://my.site1/getimage/1234567
"1234567_IMAGE"
iOS7 will download the items in the background, app can go back to sleep When done it calls
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
I then get
session.configuration.identifier
"1234567_IMAGE"
split it up and check the values
1234567_IMAGE
"1234567"
"_IMAGE" > item at location is a MP4 so save as /Documents/1234567.mp4
"_VIDEO" > item at location is a jpg so save as /Documents/1234567.jpg
If you have 3 urls to call you can have One NSURLSessionDownloadTask per NSSession
file 1 - NSSession1 > NSURLSessionDownloadTask1
file 2 - NSSession2 > NSURLSessionDownloadTask2
file 3 - NSSession3 > NSURLSessionDownloadTask3
This seems to work fine when the app is in the foreground. But I had problems when using BACKGROUND TRANSFER with BACKGROUND FETCH. The first NSSession > NSURLSessionDownloadTask1 would return and then none of the others would be called.
So safer to have multiple NSURLSessionDownloadTask in one NSSession1
file 1 - NSSession1 > NSURLSessionDownloadTask1
file 2 - > NSURLSessionDownloadTask2
file 3 - > NSURLSessionDownloadTask3
Be careful when doing this call NSSession finishTasksAndInvalidate not invalidateAndCancel
//[session invalidateAndCancel];
[session finishTasksAndInvalidate];
invalidateAndCancel will stop the session and not finish the other download tasks