0

There are several files to download in a particular viewController. When a user taps on download of a particular file, a progressView appears to show the amount of data downloaded. Also at a particular time multiple files can be downloaded. Since the file is quite large, it takes a few minutes to complete the download. The problem is that when I go to another ViewController, all the downloads stop and i have to stay on the download ViewController and wait for the download to complete. I am using NSURLSession to download data. Is there a way to get the download going even when the download ViewController is dismissed?

One option is i will transfer the code to appDelegate. Is there any other convenient way to do this task.

NSPratik
  • 4,714
  • 7
  • 51
  • 81
  • If you need some extra information that i forgot to mention here,please mention that – Sourabh Mahna Nov 14 '15 at 08:14
  • The problem is that, you might be using main thread to execute download task, why don't you use asynchronous thread to download the files in background and still send the progress update to UI on main thread? – Satyam Nov 14 '15 at 08:24
  • But the problem is for each download task,i have made an object that have several flags and properties like downloaded data,progress of progressView etc.....how it can be possible – Sourabh Mahna Nov 14 '15 at 08:39

1 Answers1

1

Try to have a look on AFNetworking https://github.com/AFNetworking/AFNetworking

You can define this part in Appdelegate but be sure to make them visible ( Properties )

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

Then in any view get them and start the download task

NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];

NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
Mohamed Mostafa
  • 1,057
  • 7
  • 12