在我的iPhone应用程序中实现空闲时间

Bar*_*K88 3 iphone timer

我想在我的应用程序中实现一个功能,以便当用户不使用应用程序5分钟时,应用程序从一开始就运行而不是用户停止的位置.

我发现plist属性'Application不在后台运行',但是这个函数让App总是从一开始运行.有没有办法可以为这个plist属性设置一个计时器或者在伪代码中做同样的事情?


更新:

提到的方式是正确的.但是我正在寻找一种解决方案,让App在应用程序进入后台后注意到空闲时间.(即按下主页按钮后).希望你能帮助我


解:

我找到了解决方案.首先,我将NSDate保存在内

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    //save date
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    [[NSUserDefaults standardUserDefaults] setObject:NSDate.date forKey:@"date"];
    [defaults synchronize];
}
Run Code Online (Sandbox Code Playgroud)

然后,当我在应用程序内部返回时,我将保存的日期与实际日期进行比较.如果时间间隔大于5分钟.该应用程序转到密码viewcontroller,强制用户再次登录!

    - (void)applicationDidBecomeActive:(UIApplication *)application
    {
        //calculate difference in time
        NSDate *time = [[NSUserDefaults standardUserDefaults] objectForKey:@"date"];

        NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:time];

        if(timeInterval >= 300){

            Password *vc = [[Password alloc] init];
            self.window.rootViewController = vc;
            [vc release];

            [self.window makeKeyAndVisible];
        }
}
Run Code Online (Sandbox Code Playgroud)

Sau*_*abh 5

如果您的应用程序运行时在iPad上没有触及使用意味着他没有正确使用您的应用程序?

然后你可以检查空闲时间,请按照下面的代码...(我从我的博客文章粘贴此代码)

步骤1 -在项目中添加一个类(IdleTimeCheck),该类是UIApplication的子类.在实现文件中,覆盖sendEvent:方法,如下所示:

- (void)sendEvent:(UIEvent *)event 
{
    [super sendEvent:event];

    // Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets.
    NSSet *allTouches = [event allTouches];
    if ([allTouches count] > 0) 
    {
        // allTouches count only ever seems to be 1, so anyObject works here.
        UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
        if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
            [self resetIdleTimer];
    }
}

- (void)resetIdleTimer 
{
    if (idleTimer) {
        [idleTimer invalidate];
        [idleTimer release];
    }

    idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTime target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO] retain];
}

- (void)idleTimerExceeded {
    NSLog(@"idle time exceeded");
    //write logic to go to start page again
}
Run Code Online (Sandbox Code Playgroud)

其中maxIdleTime和idleTimer是实例变量.

第2步 -修改main.m文件中的UIApplicationMain函数,将UIApplication子类用作主类.

int retVal = UIApplicationMain(argc, argv, @"IdleTimeCheck",nil);
Run Code Online (Sandbox Code Playgroud)

在我的博客上看到这篇文章 - http://www.makebetterthings.com/iphone/detecting-user-inactivityidle-time-since-last-touch-on-screen/