Best practices for making a queue of NSURLSessionTasks

Eric picture Eric · Dec 16, 2013 · Viewed 16k times · Source

What are the best practices for making a serial queue of NSURLSessionTasks ?

In my case, I need to:

  1. Fetch a URL inside a JSON file (NSURLSessionDataTask)
  2. Download the file at that URL (NSURLSessionDownloadTask)

Here’s what I have so far:

session = [NSURLSession sharedSession];

//Download the JSON:
NSURLRequest *dataRequest = [NSURLRequest requestWithURL:url];

NSURLSessionDataTask *task =
[session dataTaskWithRequest:dataRequest
           completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

               //Figure out the URL of the file I want to download:
               NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
               NSURL *downloadURL = [NSURL urlWithString:[json objectForKey:@"download_url"]];

               NSURLSessionDownloadTask *fileDownloadTask =
               [session downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:playlistURL]]
                              completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
                                  NSLog(@"completed!");
                              }];

               [fileDownloadTask resume];

           }
 ];

Apart from the fact that writing a completion block within another completion looks messy, I am getting an EXC_BAD_ACCESS error when I call [fileDownloadTask resume]... Even though fileDownloadTask is not nil!

So, what is the best of way of sequencing NSURLSessionTasks?

Answer

matanwrites picture matanwrites · Sep 18, 2015

You need to use this approach which is the most straight forward: https://stackoverflow.com/a/31386206/2308258

Or use an operation queue and make the tasks dependent on each others

=======================================================================

Regarding the HTTPMaximumConnectionsPerHost method

An easy way to implement a first-in first-out serial queue of NSURLSessionTasks is to run all tasks on a NSURLSession that has its HTTPMaximumConnectionsPerHost property set to 1

HTTPMaximumConnectionsPerHost only ensure that one shared connection will be used for the tasks of that session but it does not mean that they will be processed serially.

You can verify that on the network level using http://www.charlesproxy.com/, you wil discover that when setting HTTPMaximumConnectionsPerHost, your tasks will be still be started together at the same time by NSURLSession and not serially as believed.

Expriment 1:

  • Declaring a NSURLSession with HTTPMaximumConnectionsPerHost to 1
  • With task1: url = download.thinkbroadband.com/20MB.zip
  • With task2: url = download.thinkbroadband.com/20MB.zip

    1. calling [task1 resume];
    2. calling [task2 resume];

Result: task1 completionBlock is called then task2 completionBlock is called

The completion blocks might be called in the order you expected in case the tasks take the same amount of time however if you try to download two different thing using the same NSURLSession you will discover that NSURLSession does not have any underlying ordering of your calls but only completes whatever finishes first.

Expriment 2:

  • Declaring a NSURLSession with HTTPMaximumConnectionsPerHost to 1
  • task1: url = download.thinkbroadband.com/20MB.zip
  • task2: url = download.thinkbroadband.com/10MB.zip (smaller file)

    1. calling [task1 resume];
    2. calling [task2 resume];

Result: task2 completionBlock is called then task1 completionBlock is called

In conclusion you need to do the ordering yourself, NSURLSession does not have any logic about ordering requests it will just call the completionBlock of whatever finishes first even when setting the maximum number of connections per host to 1

PS: Sorry for the format of the post I do not have enough reputation to post screenshots.