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

Man*_*ani 4 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Man*_*ani 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];
Run Code Online (Sandbox Code Playgroud)

  • +1谢谢.有用.但请尝试添加代码说明,以便用户了解实际代码片段的用途. (5认同)

WDU*_*DUK 6

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

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