我为我的要求制作了一个示例应用程序,代码如下
设计:包含 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 小时。请帮我。