Search code examples
iosobjective-cipadnstimer

Calculate the Seconds duration between app did enter background to app did enter foreground


I came to know NSTimer wont work in background. My app require me to run timer even in background. What i have decide to do is calculate the seconds duration from App

- (void)applicationDidEnterBackground:(UIApplication *)application 

To

- (void)applicationWillEnterForeground:(UIApplication *)application

and subtract the seconds in my SecondsLeft variable... How to Do this. ?

viewControll.h

@property(strong,nonatomic)NSTimer *timer;

viewController.m

int secondsLeft = 1800;


-  (void)handleLongPress:(UILongPressGestureRecognizer*)gestureRecognizer
{
    if (gestureRecognizer.state == UIGestureRecognizerStateEnded)
    {
        if (isLongPressed)
        {
            isLongPressed= FALSE;
        }
        else
        {

        isLongPressed= TRUE;
        secondsLeft = minutes = seconds = 0;
        if (timerr) {
            [timerr invalidate];
        }
        timerr = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
        secondsLeft=1800;
      } 

}


    //Updates counter
- (void)updateCounter:(NSTimer *)theTimer
    {

        if(secondsLeft > 0 )
        {
            secondsLeft -- ;
            //hours = secondsLeft / 3600;
            minutes = (secondsLeft % 3600) / 60;
            seconds = (secondsLeft %3600) % 60;
            myCounterLabel.text = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
            NSLog(@"the timer %@ ",[NSString stringWithFormat:@"%02d:%02d", minutes, seconds]  );


        }
       else if (secondsLeft ==0) 
      {
           [timerr invalidate];

       }

}

Solution

  • When entering background do:

    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[NSDate date] forKey:@"TimeEnterBackground"];
    [defaults synchronize];
    

    After entering foreground again:

    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    NSDate* enteringBackground = [defaults objectForKey:@"TimeEnterBackground"];
    NSInteger timeInBackground = [[NSDate date] timeIntervalSince1970] - [enteringBackground timeIntervalSince1970];
    

    This will work even if app will be turned off while being in background