2

I am trying to correctly handle in-process NSURLSessionTasks in the event that the app enters the background (e.g from a home button press). I am currently taking the approach of copying the in-process tasks across to the background queue (see code below). I am finding however that the background tasks are behaving erratically and not always finishing. Can any spot what I might be doing wrong / advise on the best approach ?

- (void)appWillResignActive : (NSNotification *)notification {
    UIApplication *app = [UIApplication sharedApplication];

    // Register expiring background task
    __block UIBackgroundTaskIdentifier bgTaskId =
    [app beginBackgroundTaskWithExpirationHandler:^{
        bgTaskId = UIBackgroundTaskInvalid;
    }];

    [self switchToBackground];
    [app endBackgroundTask:bgTaskId];

}

- (void)appWillBecomeActive : (NSNotification *)notification {
    [self switchToForeground];
}

- (void)switchToBackground
{
    NSLog(@"Switch to background line 217 Network Manager");
    if ([state isEqualToString: kdownloadManagerStateForeground]) {
        [urlSession getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
            for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
                [downloadTask cancelByProducingResumeData:^(NSData *resumeData) {
                    NSURLSessionDownloadTask *downloadTask = [self.backgroundSession downloadTaskWithResumeData:resumeData];
                    [downloadTask resume];
                }];
            }
        }];

        state = kdownloadManagerStateBackground;
    }
}

- (void)switchToForeground
{
    if ([state isEqualToString: kdownloadManagerStateBackground]) {
        [backgroundSession getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
            for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
                [downloadTask cancelByProducingResumeData:^(NSData *resumeData) {
                    NSURLSessionDownloadTask *downloadTask = [self.urlSession downloadTaskWithResumeData:resumeData];
                    [downloadTask resume];
                }];
            }
        }];

        state = kdownloadManagerStateForeground;
    }
}
Ekta Padaliya
  • 5,743
  • 3
  • 39
  • 51
GuybrushThreepwood
  • 5,598
  • 9
  • 55
  • 113

1 Answers1

0

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.

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
NSURLSessionConfiguration *sessionConfig;
float timeout = 5 * 60.0f;

BOOL iOS8OrNew = [[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0;
if (iOS8OrNew) {
   sessionConfig = [NSURLSessionConfiguration       backgroundSessionConfigurationWithIdentifier:identifier];
   request.timeoutInterval = timeout;
}
else {
   sessionConfig = [NSURLSessionConfiguration        backgroundSessionConfiguration:identifier];
  sessionConfig.timeoutIntervalForRequest = timeout;
}

sessionConfig.HTTPMaximumConnectionsPerHost = 10;
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:sessionConfig];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request];


[manager setDidFinishEventsForBackgroundURLSessionBlock:^(NSURLSession * _Nonnull session) {
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if (appDelegate.backgroundSessionCompletionHandler) {
    void (^completionHandler)() = appDelegate.backgroundSessionCompletionHandler;
    appDelegate.backgroundSessionCompletionHandler = nil;
    completionHandler();
}
NSLog(@"All tasks are finished");
}];

For more information please see my answer : How to keep downloading new images in background even if user force quits the app in iOS objective C?

Community
  • 1
  • 1
Ekta Padaliya
  • 5,743
  • 3
  • 39
  • 51
  • 2
    I do not think this is a good answer to "Moving to a background NSURLSession from a foreground NSURLSession - Handling Tasks in Process" - the answer just gives a short introduction to background transfer. If that was the intention of the question, may be the question should be updated. – Andreas Aarsland May 08 '17 at 12:23