当App进入到后台时候,会自动调用AppDelegate代理方法
- (void)applicationDidEnterBackground:(UIApplication *)application;
接下来就是在applicationDidEnterBackground的代理方法中设置
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
[self backTask];
}
- (void)backTask{
if ([[UIApplication sharedApplication] backgroundTimeRemaining] < 61.0) {
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
}
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(test) userInfo:nil repeats:YES];
self.timer = timer;
self.i = 1;
}
- (void)test{
NSLog(@"这是第几次输出====%d",self.i);
self.i++ ;
}
这样做就可以是App进入到后台仍可以运行,看到控制输出台上一直打印。
本文介绍了一种使iOS应用在后台持续运行的方法。通过在AppDelegate中重写applicationDidEnterBackground方法,并在其中启动后台任务和定时器,可以使应用在后台继续执行特定任务。
1万+

被折叠的 条评论
为什么被折叠?



