嘿我正在开发一个应用程序,我必须每隔30秒进行一次API调用,所以我为它创建了NSTimer.但当我的应用程序进入后台计时器后3-4分钟停止发射.因此它在后台只能工作3-4分钟,但之后却没有.如何修改我的代码,以便计时器不会停止.
这是我的一些代码.
- (IBAction)didTapStart:(id)sender {
NSLog(@"hey i m in the timer ..%@",[NSDate date]);
[objTimer invalidate];
objTimer=nil;
UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
}];
objTimer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self
selector:@selector(methodFromTimer) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:objTimer forMode:UITrackingRunLoopMode];
}
-(void)methodFromTimer{
[LOG debug:@"ViewController.m ::methodFromTimer " Message:[NSString stringWithFormat:@"hey i m from timer ....%@",[NSDate date] ]];
NSLog(@"hey i m from timer ....%@",[NSDate date]);
}
Run Code Online (Sandbox Code Playgroud)
我甚至用以下内容更改了代码:
[[NSRunLoop mainRunLoop] addTimer:objTimer forMode:NSRunLoopCommonModes];
Run Code Online (Sandbox Code Playgroud)
这也不起作用.
不要将UIBackgroundTaskIdentifier任务创建为本地,并使其全局如下:
步骤1

第2步

第3步

第4步

作为本地一个松散范围和全局一个不会,我创建了一个演示并运行它一段时间,1秒重复计时器,并顺利工作.如果你面临问题,请告诉我.
我又跑了一下demo,这里有运行的日志.

所以它的工作正常,超过3分钟.另外3分钟的逻辑是正确的,但是当启动uibackgroundtask时它不应该让它杀死这个计时器的任务.
编辑部分: - bgTask = [app beginBackgroundTaskWithExpirationHandler:^ {[app endBackgroundTask:bgTask]; //删除此行,只要计时器正在运行,它就会运行,当应用程序被终止时,它会自动转储它的所有vairbles和范围.}];
检查它,让我知道它是否成功.
嘿我运行你的代码,我到达expirationHandler但在释放调试点后,计时器运行平稳.
