Search code examples
iosios6ios7background-process

why beginBackgroundTaskWithExpirationHandler ending early?


I am trying to get this to work correctly but it always seems to end early at 174 seconds (2.9 mins). I been following every tutorial possible online on how to use beginBackgroundTaskWithExpirationHandler and I don't see anything wrong with my code. I need this to end at 8.5 mins. The endBackgroundTask method doesn't even gets call before the expiration handler gets called. Is anything wrong with this?

- (void)applicationDidEnterBackground:(UIApplication *)application {

        if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
    {
        NSLog(@"Multitasking Supported");

        backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^ {
            NSLog(@"Terminated");

            //Clean up code. Tell the system that we are done.
            [application endBackgroundTask: backgroundTask];
            backgroundTask = UIBackgroundTaskInvalid;
        }];

        timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                 target:self
                                               selector:@selector(count:)
                                               userInfo:nil
                                                repeats:YES];
    }
    else
    {
        NSLog(@"Multitasking Not Supported");
    }

}



-(void)turnOffDesktops:(NSTimer *)time {
//do smth
if(count < (60*8.5)){
    NSLog(@"%d",count);
    count++;
}else{

    [application endBackgroundTask: backgroundTask];
    backgroundTask = UIBackgroundTaskInvalid;

    [timer invalidate];
    timer = nil;
    count = 0;
}

}


Solution

  • There has never been a commitment from Apple on how long you would be allowed to perform your background tasks. Historically (until iOS7), apps were given usually 10 minutes to run in the background. This is no longer the case! Watch the WWDC 2013 video on backgrounding. With the addition of the new download & upload API in NSURLSession (ability to schedule download and upload tasks on an external dedicated daemon), Apple has reduced the allowed background time significantly. They've done this because this API has always been meant for download and upload, not arbitrary tasks in the background.

    You can determine the amount of time left in background by querying - [UIApplication backgroundTimeRemaining]. You can use this to schedule your code to start at the latest possible.