Search code examples
ioscocoa-touchnsuserdefaultsnstimerstate-restoration

Set NSDate when app goes in background, save and restore it with state restoration


My app has a timer which when the app goes in the background pauses.
To still have the right time when the app comes back in the foreground, I set an NSDate called exitDate in the AppDelegate as follows:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    self.exitDate = [[NSDate alloc] init];
}

and an NSDate called reentryDate as follows:

- (void)applicationWillEnterForeground:(UIApplication *)application
{
  self.reentryDate = [[NSDate alloc] init];
}

Then I get the difference of both NSDates and add them to my timer.

This all works fine as long as the app is not terminated in the background.
If it does get terminated the App starts from the first viewController and the timer has stopped.

To fix that problem I use state restoration. Which also works fine.
Even if the app gets terminated, the app starts back at the last viewController with everything I saved beforehand.

The only thing that doesn't seem to get saved in state restoration is my exitDate even though I explicitly asked to do so.

When the app comes back, the exitDate always equals nil.

I assume it has something to do with the time the exitDate gets set which probably is after the method as follows is called:

-(void)encodeRestorableStateWithCoder:(NSCoder *)coder
{
    [coder encodeObject:self.exitDate forKey:@"UnsavedExitDateAppDelegate"];
}

-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
    self.exitDate = [coder decodeObjectForKey:@"UnsavedExitDateAppDelegate"];
}

Problem is I've tried setting exitDate in -applicationWillTerminate, -applicationDidEnterBackground and -applicationWillResignActive but everytime when the app starts back up, exitDate is nil.

Any ideas?


Solution

  • Convert NSDate to NSString using NSDateFormatter and save this String in NSUserDefaults on 'Did Enter Background'

    And on WillEnterForeground get this NSString and using same NSDateFormatter syntax convert it to NSDate.

    Or you can save in Plist and retrieve it vice versa.