views:

150

answers:

1

Hi,

In my iPhone app I have a background task that starts running when the app enters the background state. The task runs fine and is structured in a loop like this:

run. sleep for 5 min. run. sleep for 5 min.

etc.

For some reason, the task stops running after a certain amount of time... say half an hour to an hour.

Can anyone help me understand why? Here is the background task code:

- (void)applicationDidEnterBackground:(UIApplication *)application {    
NSLog(@"Application entered background state.");

if ([[NSUserDefaults standardUserDefaults] boolForKey:@"bgCheckSwitch"] == YES) {

    //UIApplication*    app = [UIApplication sharedApplication];



    // Request permission to run in the background. Provide an

    // expiration handler in case the task runs long.

    NSAssert(bgTask == UIBackgroundTaskInvalid, nil);



    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{

        // Synchronize the cleanup call on the main thread in case

        // the task actually finishes at around the same time.

        dispatch_async(dispatch_get_main_queue(), ^{

            if (bgTask != UIBackgroundTaskInvalid)

            {

                [application endBackgroundTask:bgTask];

                bgTask = UIBackgroundTaskInvalid;

            }

        });

    }];



    // Start the long-running task and return immediately.

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{



        // Do the work associated with the task.

        [someClass doSomeThing]; //The actual method performed by the task. The looping is in the method.


        dispatch_async(dispatch_get_main_queue(), ^{

            if (bgTask != UIBackgroundTaskInvalid)

            {

                [application endBackgroundTask:bgTask];

                bgTask = UIBackgroundTaskInvalid;

            }

        });

    });


}

}
+1  A: 

A background task only runs for a period of time, then the OS kills it. This is discussed in the multitasking WWDC10 videos.

jer
I think you have a total of 5 minutes processing time to complete a task. This may be upped in later revisions of IOS
Petesh
I forget exactly, but I think it's 10 minutes. I know the videos tell you.
jer
This might be handy: http://stackoverflow.com/questions/3388279/iphone-task-completion
Petesh
Yeah, my answer was the accepted one there, and I can tell you, that will get your app rejected. :)
jer
What will get the app rejected? running a background task?
No, using my suggestion in the other answer -- playing audio in the background where that audio makes no sound, and it mixes with other audio -- so the user doesn't know there's audio playing.
jer