应用程序在后台模式下执行 180 秒后重启。通过启用功能中的后台模式

App restart after 180 sec of execution in background mode. By enable the background modes in capabilities

我根据我的要求制作了一个示例应用程序,代码如下

设计:包含 1 个按钮 1 个标签

.h文件代码

@interface ViewController : UIViewController{
    int count;
    NSTimer *theTimer;
    UIBackgroundTaskIdentifier counterTask;
}

@property (weak, nonatomic) IBOutlet UILabel *theCount;

.m文件代码

- (IBAction)start:(id)sender {

    counterTask = [[UIApplication sharedApplication]
                   beginBackgroundTaskWithExpirationHandler:^{
                       // If you're worried about exceeding 10 minutes, handle it here

                       theTimer=[NSTimer scheduledTimerWithTimeInterval:0.1
                                                                 target:self
                                                               selector:@selector(countUp)
                                                               userInfo:nil
                                                                repeats:YES];

                   }];
    count=0;
    theTimer=[NSTimer scheduledTimerWithTimeInterval:0.1
                                              target:self
                                            selector:@selector(countUp)
                                            userInfo:nil
                                             repeats:YES];

}

- (void)countUp {
    if (count==100000) {
        [theTimer invalidate];
        [[UIApplication sharedApplication] endBackgroundTask:counterTask];
    } else {
        count++;
        NSString *currentCount;
        currentCount=[[NSString alloc] initWithFormat:@"%d",count];
        _theCount.text=currentCount;
    }
}

问题是,当 运行 此应用程序处于后台时(通过按主页按钮并最小化 iPhone 中的应用程序),即使在 capabilities 中启用后台模式,它也会在 180 秒后重新启动。我需要将其延长至 4 小时。请帮我。

在更高版本的 iOS 中,后台任务的限制是 3 分钟(180 秒)。您不能将此延长至 4 小时。

A​​pple 文档:

Note: Always provide an expiration handler when starting a task, but if you want to know how much time your app has left to run, get the value of the backgroundTimeRemaining property of UIApplication.

良好的 Stack Overflow Post 主题: