出于某种原因,我的计时器只在前台运行。我在这里搜索了解决方案,但找不到任何好的解决方案。我的计时器使用核心数据,每次递减后都会保存我的 timeInterval。另外,我正在发送 UILocalNotification 但这不起作用。我假设如果它在前台它不会发送警报视图..这就是我现在所拥有的:
-(IBAction)startTimer:(id)sender{
if (timer == nil) {
[startButton setTitle:@"Pause" forState:UIControlStateNormal];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
} else {
[startButton setTitle:@"Resume" forState:UIControlStateNormal];
[timer invalidate];
timer = nil;
}
}
-(void)timerAction:(NSTimer *)t
{
if(testTask.timeInterval == 0)
{
if (self.timer)
{
[self timerExpired];
[self.timer invalidate];
self.timer = nil;
}
}
else
{
testTask.timeInterval--;
NSError *error;
if (![self.context save:&error]) {
NSLog(@"couldn't save: %@", [error localizedDescription]);
}
}
NSUInteger seconds = (NSUInteger)round(testTask.timeInterval);
NSString *string = [NSString stringWithFormat:@"%02u:%02u:%02u",
seconds / 3600, (seconds / 60) % 60, seconds % 60];
timerLabel.text = string;
NSLog(@"%f", testTask.timeInterval);
}
-(void)timerExpired{
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.alertBody = @"Time is up";
localNotification.alertAction = @"Ok";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication]presentLocalNotificationNow:localNotification];
}
我真的很感激一些指导,让我的计时器在后台工作(就像苹果的计时器一样)。我不确定如何使用 NSDateComponents,因为即使应用程序在后台,我也需要更新 testTask.timeInterval ..