Set NSDate when app goes in background, save and restore it with state restoration
-
21-12-2019 - |
Question
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 NSDate
s 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.
OTHER TIPS
You can save your date or any data in shared preferences. Data would be persistence even if app is closed in background. Will definitely take off lots of pain from you as compared to your current method. Let me know if you need more explanation ..:)
Save the date to NSUserDefaults
. Don't forget to call the synchronize
method, even though this is supposed to happen automatically when the app is backgrounded, because you might be adding your date to it slightly after this happens.