离开应用程式并在iOS上返回时的计时器 [英] Timer when leaving app and returning on ios

查看:98
本文介绍了离开应用程式并在iOS上返回时的计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前在我的iOS应用上,当用户退出主屏幕并返回该应用时,它会请求在我的AppDelegate中设置的登录凭据。但是我要尝试做的是,如果用户退出应用程序并在2分钟之内返回,则计时器重置,并且用户不需要输入密码。当用户在2分钟后重新进入应用程序时,它将提醒他再次输入密码。任何帮助将不胜感激。谢谢!

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!

推荐答案

使用 NSUserDefaults 存储 NSDate 在您的应用程序委托中

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"];
}

更新:

@mun chun指出,如果应用必须执行一些处理时钟变化的操作,我们可以使用类似的

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"];
}

显然,一旦手机重启,在这种情况下我们将重置时间确保我们添加验证。还需要注意的是,应在适当的应用程序模式下删除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.

这篇关于离开应用程式并在iOS上返回时的计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆