iOS Background downloads when the app is not active iOS Background downloads when the app is not active ios ios

iOS Background downloads when the app is not active


Add below in your - (void)applicationDidEnterBackground:(UIApplication *)application

UIApplication  *app = [UIApplication sharedApplication];UIBackgroundTaskIdentifier bgTask;bgTask = [app beginBackgroundTaskWithExpirationHandler:^{         [app endBackgroundTask:bgTask]; }];

and you are good to go... I have this in one of my published download manager app

This will work just fine. You can also check how much time you have, since apple only enable 10 minutes background tasks. Use:

NSTimeInterval ti = [[UIApplication sharedApplication]backgroundTimeRemaining];NSLog(@"backgroundTimeRemaining: %f", ti); // just for debug


It is possible to start a background task when you begin the download:

Apps that are transitioning to the background can request an extra amount of time to finish any important last-minute tasks.

Executing a Finite-Length Task in the Background

However, such a task is limited to an undefined amount of execution time by the system. However, a 200Mb file download may be too large a task in this case.


You could use NSURLSession introduced in iOS 7.0 and later to continue the uploading/download of an file even when the app is suspended.

Apple documentation

The NSURLSession class and related classes provide an API for downloading content. This API provides a rich set of delegate methods for supporting authentication and gives your app the ability to perform background downloads when your app is not running or, in iOS, while your app is suspended.

And

Background sessions let you perform uploads and downloads of content in the background while your app is not running. You can create a background session configuration by calling the backgroundSessionConfiguration: method on the NSURLSessionConfiguration class.

A cool tutorial to use NSURLSession at this link.