2011-12-16 74 views
3

我想在我的應用程序中實現一個功能,以便當用戶不使用應用程序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]; 
     } 
} 

回答

2

如果應用程序背景時間超過一定時間,我會在我的某個應用程序中觸發註銷。爲此,我在應用程序委託中使用了以下方法。某些調用依賴於我的重構庫,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]; 
} 
5

如果使用未在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/

相關問題