iPhone后台任务停止运行在某个点 [英] iPhone background task stops running at some point
本文介绍了iPhone后台任务停止运行在某个点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的iPhone应用程序我有当应用程序进入后台状态开始运行一个后台任务。
任务运行良好,并在一个循环的结构是这样的:
运行。
睡5分钟。
跑。
睡5分钟。
等。
由于某些原因,该任务将停止一定时间后运行......说一个半小时到一小时。
谁能帮我明白为什么?
这里是后台任务code:
- (无效)applicationDidEnterBackground:(UIApplication的*){应用
的NSLog(@应用程序进入背景状态。);如果([[NSUserDefaults的standardUserDefaults] boolForKey:@bgCheckSwitch] == YES){ // *的UIApplication应用= [UIApplication的sharedApplication] //请求允许在后台运行。提供 //如果到期处理任务运行长。 NSAssert(bgTask == UIBackgroundTaskInvalid,无); bgTask = [应用beginBackgroundTaskWithExpirationHandler:^ { //同步的情况下,在主线程清理通话 //任务完成实际大约在同一时间。 dispatch_async(dispatch_get_main_queue(),^ { 如果(bgTask!= UIBackgroundTaskInvalid) { [应用endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; } }); }]; //开始长时间运行的任务,并立即返回。 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^ { //完成与任务相关的工作。 [SomeClass的DoSomething的]; //该任务执行的实际方法。该循环是在方法。
dispatch_async(dispatch_get_main_queue(),^ { 如果(bgTask!= UIBackgroundTaskInvalid) { [应用endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; } }); });
}}
解决方案
一个后台任务只运行了一段时间,那么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.
这篇关于iPhone后台任务停止运行在某个点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文