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

问题描述:

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

我发现plist属性'应用程序不在后台运行',但这个功能让应用程序总是从头开始运行。有没有一种方法可以为这个plist属性设置一个计时器,或者在伪代码中做类似的事情?


更新:

被提到的方式是正确的。不过,我正在寻找一种解决方案,让应用程序在进入后台后发现空闲时间。 (即在按下主页按钮之后)。希望你能帮助我走出


解决方案:

我已经找到了解决办法。首先,我保存的NSDate内

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

然后,当我返回在应用程序中,我比较保存日期的实际日期。如果时间间隔大于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]; 
     } 
} 

如果应用程序背景时间超过一定时间,我会在我的某个应用程序中触发注销。为此,我在应用程序委托中使用了以下方法。某些调用依赖于我的重构库,es_ios_utils(不是真的需要),不包括我的UserDefaults型号代码,但是这应该给你一个想法:

-(void)applicationDidEnterBackground:(UIApplication*)application 
{ 
    UserDefaults.instance.enteredBackgroundAt = NSDate.date; 
} 

-(void)applicationDidBecomeActive:(UIApplication*)application 
{ 
    if([UserDefaults.instance.enteredBackgroundAt dateByAddingMinutes:20].isPast) 
     [self logOut]; 
} 

如果使用未在iPad触摸当你的应用程序正在运行意味着他没有使用您的应用程序?

然后你可以检查空闲时间遵循下面这段代码...(我从贴我的博客张贴此代码)

第1步 -在你的项目,它的子类的UIApplication添加一个类(IdleTimeCheck) 。在实现文件中,覆盖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 
} 

其中maxIdleTime和idleTimer是实例变量。

第2步 -在main.m文件中修改您的UIApplicationMain函数,以使用您的UIApplication子类作为主类。

int retVal = UIApplicationMain(argc, argv, @"IdleTimeCheck",nil); 

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