iOS:如何在交换屏幕或屏幕睡眠时阻止计时器停止?

时间:2014-09-03 06:55:44

标签: ios iphone xcode ipad timer

我正在写一个基本的hh:mm:ss计时器应用程序。我的计时器与启动,暂停和停止选项完美配合。我的问题是,当我在应用程序上交换屏幕时,计时器停止并返回到00:00:00。

我是否需要将其保存在无论如何更新的数组中?是否有我可以实现的方法或教程可以使计时器连续计数,即使我交换屏幕,转到另一个应用程序或屏幕睡觉?

我的代码适用于任何想要实现计时器的人:

// ================= START WORK TIMER ======================= //

//Work Timer
- (void)updateWorkTimer {

if(working == false) return;

//calculate elapsed time
NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval elapsed = workSecondsAlreadyRun + currentTime - startWorkTime;

// extract out the minutes, seconds, and hours of seconds from elapsed time:
int hours = (int)(mins / 60.0);
elapsed -= hours * 60;
int workingMins = (int)(elapsed / 60.0);
elapsed -= workingMins * 60;
int secs = (int) (elapsed);

//update our label using the format of 00:00:00
self.workTimerLabel.text = [NSString stringWithFormat:@"%02u:%02u:%02u", hours, workingMins, secs];

//call updateTime every 1 second
[self performSelector:@selector(updateWorkTimer) withObject:self afterDelay:1];

}

// ============================================= ================================================== ==================

- (IBAction)startWorkButton:(id)sender {

if(working == false) {

    //start timer
    working = true;
    startWorkDate = [[NSDate alloc] init];
    startWorkTime = [NSDate timeIntervalSinceReferenceDate];

    //Set color and title for the button
    [self.startWorkButton setBackgroundColor:[UIColor blueColor]];
    [sender setTitle:@"Pause Work" forState:UIControlStateNormal];
    [self updateWorkTimer];
}
else {
    //pause timer
    workSecondsAlreadyRun += [[NSDate date] timeIntervalSinceDate:startWorkDate];
    startWorkDate = [[NSDate alloc] init];

    //Set color and title for the button
    UIColor * color = [UIColor colorWithRed:56/255.0f green:171/255.0f blue:10/255.0f alpha:1.0f];
    [self.startWorkButton setBackgroundColor: color ];
    [sender setTitle:@"Resume Work" forState:UIControlStateNormal];
    working = false;
}


}

提前致谢。

1 个答案:

答案 0 :(得分:0)

您不需要让计时器一直运行。相反,您只需计算一次应用程序再次打开后的时间间隔(应用程序转到后台后的时间),然后将其添加到计时器的值中。

为此,您需要在应用程序转到后台时使用NSUserDefaults存储计时器的当前值和当前时间([NSDate date]),并使用此数据计算应用程序在应用程序应具有的值再次开始。要拦截前往后台和前景,您应该订阅UIApplicationDidEnterBackgroundNotificationUIApplicationDidBecomeActiveNotification,因为viewDidAppearviewDidDisappear不会被调用。