我正在开发一个应用程序,在其中需要每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]);
}
我甚至用以下代码进行了更改:
我甚至用以下代码进行了更改:
[[NSRunLoop mainRunLoop] addTimer:objTimer forMode:NSRunLoopCommonModes];
这也没有起作用。