我正在使用beginBackgroundTaskWithExpirationHandler为应用程序在后台运行花费10分钟的额外时间。但是如果应用程序在提供的10分钟内达到前景,我需要停止此后台任务。我的代码如下
- (void)applicationDidEnterBackground:(UIApplication *)application
{
bgTask = [application beginBackgroundTaskWithExpirationHandler: ^ {
NSLog(@"invalidate back task in didenter %@",[application backgroundTimeRemaining]);
if (bgTask != UIBackgroundTaskInvalid) {
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
}];
//Background tasks require you to use asyncrous tasks
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"\n\nRunning in the background inside DidEnterBackground %f!\n\n", [application backgroundTimeRemaining]);
while ([application backgroundTimeRemaining] > 1.0) {
NSLog(@"\n\nRunning in background %f!\n\n", [application backgroundTimeRemaining]);
sleep(5);
}
[application endBackgroundTask: bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
当应用程序出现前景时,我正在结束这样的后台任务
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
bgTask在.h文件中全局声明。当应用程序进入前景时,它仍然运行后台任务,并将backgroundTimeRemaining显示为长整数值。我没有得到如何停止后台任务请帮助我。
由于