【发布时间】:2013-08-03 23:06:52
【问题描述】:
由于某种原因,我的计时器只在前台运行。我在这里搜索了解决方案,但找不到任何好的解决方案。我的计时器使用核心数据,每次递减后都会保存我的 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];
}
非常感谢一些指导,让我的计时器在后台工作(就像 Apple 的计时器一样)。我不确定如何使用 NSDateComponents,因为即使应用程序在后台,我也需要更新 testTask.timeInterval..
【问题讨论】:
-
当您的应用程序处于后台时,您无法让计时器运行。如果您尝试显示倒计时,则需要保存应用程序进入后台的时间,并在您再次激活时重新显示时使用该时间。 SO上有很多关于这个问题的帖子。
-
你试过了吗?
[[UIApplication sharedApplication] performSelector:@selector(presentLocalNotificationNow:) withObject:localNotification afterDelay:1.0];其中 1.0 是您要等待的时间(以秒为单位)。
标签: iphone ios objective-c nstimer uilocalnotification