Currently on my iOS app, when the user exits to the home screen and goes back into the app, it requests a login credentials which is set in my AppDelegate. But what I am trying to do is if the user goes out of the app and back in within for example 2 minutes, the timer resets and the user does not need to input his password. When the user goes back into the app after 2 minutes, it will alert him to input the password again. Any help will be greatly appreciated. Thanks!
Use NSUserDefaults
to store the NSDate
in your app delegate
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"myDateKey"];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
NSDate *bgDate = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey: @"myDateKey"];
if(fabs([bgDate timeIntervalSinceNow]) > 120.00) {
//logout
}
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"myDateKey"];
}
Update:
Good point by @mun chun if the app has to implement something to handle clock changes we can use something like this
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[NSUserDefaults standardUserDefaults] setFloat: [[NSProcessInfo processInfo] systemUptime] forKey:@"myDateKey"];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
float bgTime = [[NSUserDefaults standardUserDefaults] floatForKey: @"myDateKey"];
if(fabs([[NSProcessInfo processInfo] systemUptime] - bgTime) > 120.00) {
//logout
}
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"myDateKey"];
}
Obviously once the phone restarts the time will be reset in that case we have to make sure we add validation. Also to note is that the myDateKey should be removed in appropriate application modes.