0

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

设计:包含 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 中的应用程序),即使在功能中启用后台模式,它也会在 180 秒后重新启动。我需要将其延长至 4 小时。请帮我。

4

1 回答 1

0

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

苹果文档:

注意:启动任务时始终提供过期处理程序,但如果您想知道应用程序还剩多少时间可以运行,请获取 UIApplication 的 backgroundTimeRemaining 属性的值。

关于该主题的良好堆栈溢出帖子:

Apple 允许后台任务运行多长时间?

于 2018-02-17T05:01:27.050 回答