我正在尝试使其正常工作,但它似乎总是在174秒(2.9分钟)之前结束。我一直在网上尽可能地学习有关如何使用beginBackgroundTaskWithExpirationHandler的所有教程,但是我的代码没有发现任何问题。我需要在8.5分钟后结束。在调用到期处理程序之前,甚至没有调用endBackgroundTask方法。这有什么问题吗?
- (void)applicationDidEnterBackground:(UIApplication *)application {
if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
{
NSLog(@"Multitasking Supported");
backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^ {
NSLog(@"Terminated");
//Clean up code. Tell the system that we are done.
[application endBackgroundTask: backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
}];
timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(count:)
userInfo:nil
repeats:YES];
}
else
{
NSLog(@"Multitasking Not Supported");
}
}
-(void)turnOffDesktops:(NSTimer *)time {
//do smth
if(count < (60*8.5)){
NSLog(@"%d",count);
count++;
}else{
[application endBackgroundTask: backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
[timer invalidate];
timer = nil;
count = 0;
}
}
最佳答案
苹果公司从未 promise 过将允许您执行后台任务多长时间。从历史上讲(直到iOS7),应用通常在后台运行10分钟。 不再是这种情况! 观看有关背景的WWDC 2013视频。通过在NSURLSession
中添加新的下载和上传API(能够在外部专用守护程序上安排下载和上传任务的能力),Apple大大减少了允许的后台时间。他们之所以这样做,是因为该API一直用于下载和上传,而不是在后台执行任意任务。
您可以通过查询- [UIApplication backgroundTimeRemaining]
来确定后台剩余的时间。您可以使用它来安排代码以尽可能最早的时间开始。
关于ios - 为什么beginBackgroundTaskWithExpirationHandler提前结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20723112/