As the title says: How do I determine how long my iOS App has been closed or has been in the background? I need to know this since I want to call a method if the app has been closed or has been in the background for more than 3 hours.
Asked
Active
Viewed 1,701 times
2
-
1Record the time it is closed/put in background into a file and then load this file during startup/put in foreground? Doesn't sound very difficult to me. – trojanfoe Nov 11 '13 at 16:51
-
Why are you wanting to do this? Is it because you want to nag people to use your app? If so... please do us a favour and just don't release your app. – Fogmeister Nov 11 '13 at 16:56
-
Haha, no, I do not want to nag people. – 7c9d6b001a87e497d6b96fbd4c6fdf Nov 11 '13 at 16:58
2 Answers
3
You can track the time application was is background/killed by saving times in NSUserDefaults and then use them once your application is re-launched. Try this code (I have formatted the dates as I used them further in my app in the formatted way. You may choose to ignore date formatting.):
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSString *backGroundTime = [dateFormat stringFromDate:[NSDate date]];
[[NSUserDefaults standardUserDefaults]setValue:backGroundTime forKey:@"backGroundTime"];
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSString *foreGroundTime = [dateFormat stringFromDate:[NSDate date]];
NSString *backGroundTime = [[NSUserDefaults standardUserDefaults]valueForKey:@"backGroundTime"];
[self minCalculation_backgroundtime:backGroundTime forgroundTime:foreGroundTime];
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
// Call this method to calculate the duration of inactivity
-(void)minCalculation_backgroundtime:(NSString *)backgroundTime forgroundTime:(NSString *)foreGroundTime
{
NSDateFormatter *dateformat = [[NSDateFormatter alloc]init];
[dateformat setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
NSDate *lastDate = [dateformat dateFromString:foreGroundTime];
NSDate *todaysDate = [dateformat dateFromString:backgroundTime];
NSTimeInterval lastDiff = [lastDate timeIntervalSinceNow];
NSTimeInterval todaysDiff = [todaysDate timeIntervalSinceNow];
NSTimeInterval dateDiff = lastDiff - todaysDiff;
int min = dateDiff/60;
NSLog(@"Good to see you after %i minutes",min);
}
-
2Why store formatted date/time when "timeinterval since 1970" is a single floating point number, which doesn't require formatting or parsing? It's also more accurate. – trojanfoe Nov 11 '13 at 16:54
-
That is the piece I used in my project. You may choose to ignore the formatting. Idea here is to give you a way to achieve this. Please feel free to modify as per your convenience. – Abhinav Nov 11 '13 at 16:57
-
Well I bet you could cut 80% of that code out by storing just the time interval. BTW, I am not the OP. – trojanfoe Nov 11 '13 at 16:58
-
You win this bet in this case :-). But I had used the formatted dates in my app contexts. – Abhinav Nov 11 '13 at 17:00
-
3You can even store the raw `NSDate` object. No need to convert it a time interval. – rmaddy Nov 11 '13 at 17:13
-
Agree and I have mentioned that in my answer. That was a quick piece from my project and I had used formatted dates :-)! – Abhinav Nov 11 '13 at 17:21
2
You can save time in NSUSerDefaults
for going in background. When your app comes back on foreground, you can get difference of that time.
When your app will go in background this method will execute - (void)applicationDidEnterBackground:(UIApplication *)application
and when it will come back in foreground - (void)applicationWillEnterForeground:(UIApplication *)application
this method will get call.

Adnan Aftab
- 14,377
- 4
- 45
- 54
-
Don't forget the case that your app may have crashed without calling `applicationDidEnterBackground:`. The user can also kill your app without letting you go into the background (double-tap home, and then swipe to kill). In general, C_X's approach will still work, since you will look at the *last* value (which will be even older), but you need to keep these cases in mind. If you're using "when did I go into the background" as a proxy for something else like "when did I last talk to the server," I would track the thing you really care about rather than when you go into the background. – Rob Napier Nov 11 '13 at 17:19
-
Also a useful hint-sheet on when the various methods are called: http://stackoverflow.com/questions/3712979/applicationwillenterforeground-vs-applicationdidbecomeactive-applicationwillre – Rob Napier Nov 11 '13 at 17:25