如何在应用程序的后台运行计时器?

时间:2012-10-16 14:12:51

标签: iphone

我想减少时间倒计时。因此,如果用户最小化应用程序,则应用程序加载后台如何在应用程序后台运行计时器?我使用以下代码。当app最小化时,计时器停止。请帮帮我。

        timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerCountDown) userInfo:nil repeats:YES];

- (void)timerCountDown
{
    if(secondsLeft > 0 ) {
        secondsLeft -- ;
        hours = secondsLeft / 3600;
        minutes = (secondsLeft % 3600) / 60;
        seconds = (secondsLeft %3600) % 60;
    }
}

2 个答案:

答案 0 :(得分:29)

我得到了答案,它工作得很好。

UIBackgroundTaskIdentifier bgTask =0;
UIApplication  *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
}];

timer = [NSTimer
               scheduledTimerWithTimeInterval:1.0
               target:self
               selector:@selector(timerCountDown:)
               userInfo:nil
               repeats:YES];

答案 1 :(得分:6)

应用程序不会永远在后台运行;您无法保证在应用关闭时计时器将继续运行。

在app delegate中,在applicationDidEnterBackground中,保存任何允许计时器在applicationWillEnterForeground时继续的数据。在您的特定情况下,使背景上的计时器无效,并在进入前景时再次启动它。使用secondsLeft,您可能希望能够通过NSDates的差异来计算,并保存开始日期和结束日期。

相关问题