简体   繁体   中英

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

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
        }
    }
}

Write the time and date to NSUserDefaults when the application enters the background or is quit. Then read that time and date back from NSUserDefaults in the applicationWillEnterForeground and compare. If it is more than 1 hour (or whatever you set your timeout to be) then display the log in screen.

Save the time when the app enters background to NSUserDefaults. then read it when it re-enters foreground.

In applicationWillEnterForeground if the time difference is over 1 hour you would set a flag or post a notification. ie you could have a method in your app delegate that logs the user out, or you could have a check for a flag in viewWillAppear which if necessary logs the user out.

First set the timer in method applicationdidFinishLaunching:

Now check the time in method applicationDidBecomeActive: this is called every time when user start the app again.

If time is greater than ex(1 hour) then reset timer and logout the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM