2011-12-23 83 views
3

在我的iPhone定時器應用程序中,定時器:如何在後臺保持定時器活動

其中定時器應該在後臺運行。

所以, 我已經設置的appdelegate它完美... 有了,我打電話從視圖控制器,這使得計時器活着的方法的通知。

看看一些代碼...

應用程序委託

- (void)applicationDidEnterBackground:(UIApplication *)application 
{ 
    /* 
    Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 
    */ 

    NSLog(@"Time Remaining %d",(self.viewController.totalSeconds-self.viewController.totalCount)); 
    [self.viewController selectandnotify:(self.viewController.totalSeconds-self.viewController.totalCount)]; 
    [self.viewController stopTimer]; 
    [self.viewController startTimerAction]; 

} 

在這裏,我調用該方法startTimerAction方法,它是在我的視圖控制器......看看這個。 ..

-(void)startTimerAction 
{ 
timer_main = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:@selector(ShowActicity) userInfo:nil repeats:YES]; 
} 

哪家的NSTimer

這裏每次

- ShowActivity後每一秒......這下面是我的視圖控制器方法將調用...

-(void)ShowActicity 
{ 

    NSLog(@"Total Counts %d",totalCount); 
    if (totalCount == totalSeconds) { 
     if ([timer_main isValid]) { 
      [timer_main invalidate]; 
      isTimeOver = YES; 
      [self generateLog]; 
     } 
    } else { 
     totalCount++; 

     seconds =seconds + 1; 
     if(seconds > 59) 
     { 
      minutes = minutes + 1; 
      seconds= 0; 
     } 

}

如何每次調用此方法從視圖控制器.....

  • 我怎樣才能每次從appdelegate調用showActivity方法...

    • 我應該使用委託該

    • 我應該建立在我的appDelegate showActivity和定時器..

  • 其實我想這個應用程序在運行應用程序時查看交換機。 ....

我想如果我讓委託是一個很好的選擇?

任何其他方式....請有一些建議

回答

4

一般都用這個代碼運行。在背景定時器背景不起作用

- (void)applicationDidEnterBackground:(UIApplication *)application 
{ 
    UIApplication* app = [UIApplication sharedApplication]; 

    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
     [app endBackgroundTask:bgTask]; 
     bgTask = UIBackgroundTaskInvalid; 
    }]; 

    // Start the long-running task and return immediately. 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

     // Do the work associated with the task. 
     [self startTimerAction]; 
     [app endBackgroundTask:bgTask]; 
     bgTask = UIBackgroundTaskInvalid; 
    }); 
} 

http://developer.apple.com/library/ios/#DOCUMENTATION/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW3

+0

謝謝薩欽它一個很好的答案,我的問題解決完美...再次感謝... – 2011-12-23 10:40:51

+0

歡迎兄弟們------ – Tendulkar 2011-12-23 10:43:58

+0

什麼是bgTask?請告訴我.. – Mani 2012-10-16 14:50:55

相關問題