ios - 为什么beginBackgroundTaskWithExpirationHandler提前结束?

标签 ios ios6 ios7 background-process

我正在尝试使其正常工作,但它似乎总是在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/

相关文章:

ios - 无法使用 gradle 在 iPhone 模拟器中启动 libgdx ios/robovm 构建

ios - Swift:禁用 UITableViewCell 上的触摸

ios - UIViewPropertyAnimator 未按预期工作

ios - 如何获取应用商店中显示的点赞数

ios - 底部工具栏显示在 iPhone 但不是 iPad

iphone - 在 IOS 7 中,UITextView offsetFromPosition : toPosition: always return 0 with arguments of UITextPositions returned from UITextView characterRangeAtPoint

objective-c - iOS 7 : Multipeer connectivity - Multiple Sessions?

iphone - 如何使用 didFinishPickingMediaWithInfo 从视频中查找 "Selected frames"的开始和结束持续时间?

objective-c - 用 UIImage 组合 UIActivityTypeMessage

iphone - 使用 Google Maps for iOS 检索多个标记的位置、标题和片段