How to run the timer in background of the application?
Asked Answered
B

2

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;
    }
}
Brynne answered 16/10, 2012 at 14:12 Comment(1)
Check out this thread on SO for other options.Albacore
B
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];
Brynne answered 17/10, 2012 at 11:17 Comment(4)
+1 Thanks. It works. But please try to add explanation of your code so users can understand what actually code snippet is doing.Hildredhildreth
@Brynne it is working like a charm but is it a healthy solution?Ischia
Yes. I am used like this and released the app. It working fine in app store.Brynne
I guess the timer will cease after certain interval of time (mostly 3 min) as the closure where 'endBackgroundTask' gets called.Luane
C
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.

Conceivable answered 16/10, 2012 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.