Reputation: 2255
How can I tell the time from the last time my app was open? Can this still be monitored even my app is not running in the background?
Thanks.
Upvotes: 8
Views: 5661
Reputation: 12714
Put something like
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"kLastCloseDate"];
in both
- (void)applicationWillTerminate:(UIApplication *)application
- (void)applicationDidEnterBackground:(UIApplication *)application
Then check the difference at startup:
NSDate *lastDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"kLastCloseDate"];
NSTimeInterval timeDiff = [[NSDate date] timeIntervalSinceDate:lastDate];
// your stuff
in both
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- (void)applicationWillEnterForeground:(UIApplication *)application
Upvotes: 19
Reputation: 49386
In your application delegates - (void)applicationDidEnterBackground:(UIApplication *)application
method, just write the current time to a file. Then, in either applicationWillEnterForeground:
or applicationDidFinishLaunching
, read this file and compare with the current time. The difference will tell you how long since your application was last foremost.
Upvotes: 1