4

I want to reduce the count down of the time. So If the user minimize app then app loading the background. How can run the timer in application background? I am using the below code. When app is minimized timer is stopped. Please help me.

        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;
    }
}
Mani
  • 1,310
  • 1
  • 20
  • 40
  • Check out [this thread on SO](http://stackoverflow.com/questions/8304702/how-do-i-create-a-nstimer-on-a-background-thread) for other options. – lucasart Mar 10 '14 at 08:50

2 Answers2

29

I got the answer, its working perfectly.

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];
Mani
  • 1,310
  • 1
  • 20
  • 40
  • 5
    +1 Thanks. It works. But please try to add explanation of your code so users can understand what actually code snippet is doing. – rohan-patel Jan 03 '13 at 13:32
  • @Mani it is working like a charm but is it a healthy solution? – death7eater Jul 21 '13 at 13:40
  • 1
    Yes. I am used like this and released the app. It working fine in app store. – Mani Jul 22 '13 at 08:56
  • I guess the timer will cease after certain interval of time (mostly 3 min) as the closure where 'endBackgroundTask' gets called. – Sujal Jun 14 '18 at 10:02
6

Applications don't run in the background forever; you can't guarantee that the timer will continue when the app is closed.

In the app delegate, within applicationDidEnterBackground, save any data that allows the timer to continue when the applicationWillEnterForeground. In your particular case, invalidate the timer on backgrounding, and start it up again on it entering the foreground. With your secondsLeft, you may want to be able to calculate that via a difference in NSDates, and save the start and end dates.

WDUK
  • 18,870
  • 3
  • 64
  • 72