如果计时器在前台,我有一个计时器可以完美运行。完美递减,停在0。但是,当我点击home键进入主屏幕,然后等待本地通知弹出,然后我点击通知时,时间间隔变成了42亿(限制对于无符号长整数)。基本上,它不会停在 0。我不知道如何解决这个问题。我尝试将其设为常规 NSInteger 并检查间隔是否低于 0,但我得到了相同的结果。
-(IBAction)startTimer:(id)sender{
if (!timer) {
[startButton setTitle:@"Start" forState:UIControlStateNormal];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
date = [NSDate date];
} else {
[startButton setTitle:@"Stop" forState:UIControlStateNormal];
anotherTimeInterval = testTask.timeInterval;
[timer invalidate];
timer = nil;
}
}
-(void)timerAction:(NSTimer *)t
{
NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:date];
if (testTask.timeInterval > 0){
NSError *error;
if (![self.context save:&error]) {
NSLog(@"couldn't save: %@", [error localizedDescription]);
}
NSUInteger seconds = (NSUInteger)round(anotherTimeInterval-interval);
NSString *string = [NSString stringWithFormat:@"%02u:%02u:%02u",
seconds / 3600, (seconds / 60) % 60, seconds % 60];
testTask.timeInterval = seconds;
timerLabel.text = string;
NSLog(@"%@", string);
} else {
NSLog(@"timer ended");
[self.timer invalidate];
self.timer = nil;
[self timerExpired];
}
}
-(void)applicationWillResignActive:(UIApplication *)application{
if (timer){
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:testTask.timeInterval];
localNotification.alertBody = @"Time is up";
localNotification.alertAction = @"Ok";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
}