Michael
Michael

Reputation: 6899

NSURLSessionDownloadTask - Serially download multiple files

What is the best practice to download a list of files serially with NSURLSessionDownloadTask?

For example, is it best to begin a new NSURLSession on the completion of the previous download?

- (void)startDownloadWithRequest:(NSURLRequest *)request{

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];

    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request];
    [downloadTask resume];

}

Then in the delegate upon completion call -startDownload again with a different request.

- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{

    NSURL *url = [NSURL URLWithString:@"http://asdf.com/Hello_world.pdf"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    [self startDownload:request];

}

Would this method of chaining downloads cause the stack to grow with each subsequent request since the call to -startDownloadWithRequest in occurring on the completion of the previous download?

I have searched SO and other website, but couldn't find an alternative to serially downloading files with NSURLSessionDownloadTask.

Upvotes: 2

Views: 1545

Answers (1)

joakim
joakim

Reputation: 4041

There is certainly no need to create new session (and configuration) objects if the tasks to be performed are under the same rules in terms of configuration e.g. timeout, cookie and caching policies etc

On the contrary, that would be counterproductive, why would you allocate new objects that do the exact same thing? You can even override certain policies of a session's configuration via NSUrlRequest if the configuration does not impose a stricter policy.

As for best practices for downloading files serially, your setup looks solid.

Upvotes: 1

Related Questions