Ios 限制后台时间

Ios 限制后台时间,ios,grand-central-dispatch,Ios,Grand Central Dispatch,当用户进入后台状态时,我需要运行一些代码。当我在iOS 9上进入后台时,我得到的默认时间是10秒。我需要的不仅仅是这些,所以我发现这段代码将把时间延长到3分钟: - (void)extendBackgroundRunningTime { if (_backgroundTask != UIBackgroundTaskInvalid) { // if we are in here, that means the background task is already runni

当用户进入后台状态时,我需要运行一些代码。当我在iOS 9上进入后台时,我得到的默认时间是10秒。我需要的不仅仅是这些,所以我发现这段代码将把时间延长到3分钟:

- (void)extendBackgroundRunningTime {
    if (_backgroundTask != UIBackgroundTaskInvalid) {
        // if we are in here, that means the background task is already running.
        // don't restart it.
        return;
    }
    NSLog(@"Attempting to extend background running time");

    __block Boolean self_terminate = YES;

    _backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"DummyTask" expirationHandler:^{
        NSLog(@"Background task expired by iOS");
        if (self_terminate) {
            [[UIApplication sharedApplication] endBackgroundTask:_backgroundTask];
            _backgroundTask = UIBackgroundTaskInvalid;
        }
    }];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"Background task started");

        while (true) {
            NSLog(@"background time remaining: %8.2f", [UIApplication sharedApplication].backgroundTimeRemaining);
            [NSThread sleepForTimeInterval:1];
        }

    });
}

然而,我的任务并不需要所有这些额外的时间,我希望尽可能节省电池。是否有任何方法可以使用此代码或类似代码获得1分钟的后台时间,或10到180秒之间的其他值?

完成后台处理后,应调用
endBackgroundTask:
。如果您在分配给您的3分钟时间之前完成,则应提前结束后台处理,并让iOS暂停您。我还没有对它进行测试以进行验证,但这正是文档所建议的。

在这段时间内,我还有其他进程在运行。即使我手动终止此任务,应用程序仍处于唤醒状态。我需要在1分钟后休眠整个应用程序。你无法控制剩余的后台剩余时间。您只能开始/结束后台任务。有时180秒可以延长,我无法复制它,但这是随机发生的。