且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iPhone后台任务停止运行在某个点

更新时间:2023-12-04 09:07:58

一个后台任务只运行了一段时间,那么OS杀死它。这是在多任务WWDC10视频讨论

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;

            }

        });

    });


}

}

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