2

I have a timer that have to count up to 8 hours (28800 second) after that it should be released

im wondering how to keep the timer running at the background and/or when application is closed?

this is the NSTimer :

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

and this is my condition :

 counter++;

if (counter >= 28800) {
    [stopWatchTimer invalidate];
    counter =0;

    timeLabel.text = @"Time Out";
}
Mutawe
  • 6,464
  • 3
  • 47
  • 90

2 Answers2

2

You can't - once your app is closed then it's not running anymore so the timer won't be running either.

Take a look at local notifications?

deanWombourne
  • 38,189
  • 13
  • 98
  • 110
2

When application goes in background, In –(void)applicationDidEnterBackground: application delegate method add current counter value and current time in nsuserdefault.

Now when application becomes active before that –(void)applicationWillEnterForeground: will called so in that method get total seconds application was in background ie (current time of application) - (time when application went background which is stored in nsuserdefault) calculate in seconds

so add this also in –(void)applicationWillEnterForeground :

 if((seconds calculated) > (28800 - (current counter value stored in nsuserdefault)))
 {
    // stop timer as it has gone beyond eight hours
 } 
 else
 {
  // continue task
 }
Paresh Navadiya
  • 38,095
  • 11
  • 81
  • 132