2013-08-23 51 views
0

我想觸發一段時間後的動作(生產時間爲30分鐘),現在我正在使用NSTimer s scheduledTimerWithTimeInterval。在測試過程中(超時時間爲20秒,而不是1800秒)一切都很正常。在debbuging模式下(從XCode運行),一切似乎都很好,因爲設備不會自動鎖定。但在現實生活中,當應用程序在設備上運行時,自動鎖定(正是自動鎖定,觸發鎖定按鈕不會)「凍結」定時器(或至少將定時器觸發器以某種方式移到將來)。自動鎖定ios設備,NSTimer和scheduledTimerWithTimeInterval

我可以處理這種情況嗎?當然,我可以在UIApplication sharedApplication中禁用idleTimer,但是當應用程序進入後臺模式時,ipad仍然可以自動鎖定。

+0

什麼行動?你只是想通知用戶,然後執行行動,如果他們接受通知? – Wain

回答

2

其實你可以,

首先,對於「startTimeOfMyExoticTimer」創建默認值NSUserDefaults的:

[[[NSUserDefaults] standardDefaults] setObject:[NSDate date] forKey:@"startTimeOfMyExoticTimer"]; 

然後檢查一個定時器的踢,如果有效時間範圍是在:

[NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(checkIfTimeIsOver) userInfo:nil repeats:YES]; 

然後實現你的檢查方法:

-(void)checkIfTimeIsOver{ 
    NSDate * now = [NSDate date]; 
    NSDate * startTime = [[NSUserDefaults standardDefaults] objectForKey:@"startTimeOfMyExoticTimer"]; 

    // Here compare your now and startTime objects. (subsract them) and see the difference between them. If your time range is to be set on 30 seconds. Then you should check if the time difference between those objects are bigger than 30 seconds. 

} 

這將是工作,即使設備處於鎖定狀態,應用程序是在後臺等

這種方式爲我工作,希望它會爲你工作太

0
//Implement this block help your application run background about 10 minutes  

@interface AppDeledate(){ 
    UIBackgroundTaskIdentifier backgroundTaskId; 
} 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    // if missing interval exist > start timer again and set missing interval to 0 
} 
- (void)applicationDidEnterBackground:(UIApplication *)application { 
     NSLog(@"Did Enter Background"); 

     backgroundTaskId = [application beginBackgroundTaskWithExpirationHandler:^{ 
      NSLog(@"Background Task Expired !!!\n"); 

      [application endBackgroundTask:backgroundTaskId]; 
      backgroundTaskId = UIBackgroundTaskInvalid; 
        //save missing interval to NSUserDefault 
     }]; 
    } 

    - (void)applicationWillEnterForeground:(UIApplication *)application 
    { 
     NSLog(@"Will Enter Foreground"); 

     if (backgroundTaskId && backgroundTaskId != UIBackgroundTaskInvalid) { 
      [application endBackgroundTask:backgroundTaskId]; 



    backgroundTaskId = UIBackgroundTaskInvalid; 
     } 

    } 
相關問題