Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking how long iPhone App has been in background when coming into foreground

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

like image 813
Andy Avatar asked Feb 29 '12 09:02

Andy


1 Answers

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
        }
    }
}
like image 150
Rok Jarc Avatar answered Sep 18 '22 11:09

Rok Jarc