I have an app that requires a user login to use it. I have a value of X number of minutes that if the app was inactive for that long, it will log the user out so when they start the app next, they would have to enter their login info again.
Is there an easy and efficient way to do this? I’m thinking I have to add an NSTimer to my AppDelegate and add some logic in the didFinishLaunchingWithOptions method. I have the minutes stored as an int in NSUserDefaults.
For example, if the app has not been used in 60 minutes, then log the user out (it won’t really log the user out then, but the next time the app is launched it will log the user out and show the login screen, etc).
Edit:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSDictionary *userContextDictionary = [dataSource fetchUserContext];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setDouble:[[userContextDictionary valueForKey:@"autologout_idle_timeout"] doubleValue] forKey:@"timeoutLength"];
double timeDifference = ([[NSDate date] timeIntervalSince1970] - [userDefaults doubleForKey:@"Close Time"]) / 60;
if (timeDifference > [userDefaults doubleForKey:@"timeoutLength"]) {
NSLog(@"Timeout Hit");
} else {
NSLog(@"No Timeout");
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
double currentTime = [[NSDate date] timeIntervalSince1970];
[userDefaults setDouble:currentTime forKey:@"Close Time"];
}
Simply store the time that the app is closed, and then check it when it becomes active. If the difference between the two is too high, require re-login. Otherwise continue the app where it left off.
In your
applicationDidEnterBackgroundmethod or similar:And then in the
applicationWillEnterForegroundanddidFinishLaunchingWithOptions(to cover opening from a closed state and opening from background):