How to download multiple files by NSURLSessionDownloadTask

1.1k views Asked by At

iOS 8, XCode 6.3.2

I want to download multiple files serially. In the wake of the Push notification, APP will start BackgroudDownload by NSURLSessionDownloadTask. After the First BackgroudDownload process has been completed, APP want to start Second process, but Second BackgroudDownload process does not start.

Code is below

// This method is called by Push Notification

- (void)startBackgroundDownload
{
    // Session
    NSURLSessionConfiguration *configFirst = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.test.first"];
    sessionFirst = [NSURLSession sessionWithConfiguration:configFirst delegate:self delegateQueue:nil];

    NSURLSessionConfiguration *configSecond = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.test.second"];
    sessionSecond = [NSURLSession sessionWithConfiguration:configSecond delegate:self delegateQueue:nil];

    // Start First Download
    NSURLRequest *requestFirst = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://xxxxx/first.zip"]];
    NSURLSessionDownloadTask *downloadTaskFirst = [sessionFirst downloadTaskWithRequest:requestFirst];
    [downloadTaskFirst resume];
}

// Finish Download

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    if (session == sessionFirst) {
        NSURLRequest *requestSecond = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://xxxxx/second.zip"
        NSURLSessionDownloadTask *downloadTaskSecond = [sessionSecond downloadTaskWithRequest:requestSecond];
        [downloadTaskSecond resume];
    } else if (session == sessionSecond) {
        NSLog(@"all finish");
    }
}

The First is successful, and the Second is fail (not start). I want advice to pursue the cause. Thank you for any help you can provide.

1

There are 1 answers

0
Pravin Tate On

downloading task is divide in perfect part like as follow.

  1. First make one array of zip files which you want to download.
  2. Initialise session object
  3. Write one method which can get URL and "startDownloading"
  4. In delegate method (successful download) called unzip that file. remove first object of zip array and again called "startDownloading" method and its call until your array count is greater than zero

I hope you will understand what I want to explain here.