开发者

iPhone background task stops running at some point

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 == UIBackgroundTaskInval开发者_如何学运维id, 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;

            }

        });

    });


}

}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜