I have an iPhone App which allows users to log in and interact with a web service. I would like to have the ability for the user to be automatically logged out after a period of inactivity...more specifically if the App has been in the background for over a period of time (for example 1 hour).
I would ideally like to run a check in the App Delegate method applicationWillEnterForeground that checks how long the app has been in the background and then if it has been over the time allowed, take them to the log in screen.
How would I run this check in the above method? I would appreciate some sample code.
If this is not the best way to achieve my requirements then suggestions also welcome!
Many thanks in advance
Andy
You can use this:
- (void)applicationWillResignActive:(UIApplication *)application
{
NSDate *thisMagicMoment = [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:thisMagicMoment forKey:@"lastMagicMoment"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
NSDate *thisMagicMoment = [NSDate date];
NSDate *lastMagicMoment = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"lastMagicMoment"];
if (lastMagicMoment==nil)
{
NSLog (@"First launch!");
}
else
{
NSTimeInterval timeOfNoMagic = [thisMagicMoment timeIntervalSinceDate:lastMagicMoment]/3600.0;
NSLog (@"Application was in background for %.1f hours", timeOfNoMagic);
//do your stuff - treat NSTimeInterval as double
if (timeOfNoMagic > 1.0)
{
//logout
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With