2014-09-29 19 views
0

我來了解NSTimer不會在後臺工作。我的應用程序要求我在後臺運行計時器。我有什麼決定做的是從應用程序計算應用程序之間的秒數持續時間進入背景應用程序確實進入前景

- (void)applicationDidEnterBackground:(UIApplication *)application 

計算時間要

- (void)applicationWillEnterForeground:(UIApplication *)application 

和減去秒我SecondsLeft變量...如何做到這一點。 ?

viewControll.h 

@property(strong,nonatomic)NSTimer *timer; 

viewController.m 

int secondsLeft = 1800; 


- (void)handleLongPress:(UILongPressGestureRecognizer*)gestureRecognizer 
{ 
    if (gestureRecognizer.state == UIGestureRecognizerStateEnded) 
    { 
     if (isLongPressed) 
     { 
      isLongPressed= FALSE; 
     } 
     else 
     { 

     isLongPressed= TRUE; 
     secondsLeft = minutes = seconds = 0; 
     if (timerr) { 
      [timerr invalidate]; 
     } 
     timerr = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES]; 
     secondsLeft=1800; 
     } 

} 


    //Updates counter 
- (void)updateCounter:(NSTimer *)theTimer 
    { 

     if(secondsLeft > 0) 
     { 
      secondsLeft -- ; 
      //hours = secondsLeft/3600; 
      minutes = (secondsLeft % 3600)/60; 
      seconds = (secondsLeft %3600) % 60; 
      myCounterLabel.text = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds]; 
      NSLog(@"the timer %@ ",[NSString stringWithFormat:@"%02d:%02d", minutes, seconds] ); 


     } 
     else if (secondsLeft ==0) 
     { 
      [timerr invalidate]; 

     } 

} 

回答

2

當進入後臺做:

NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; 
[defaults setObject:[NSDate date] forKey:@"TimeEnterBackground"]; 
[defaults synchronize]; 

再次進入前臺後:

NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; 
NSDate* enteringBackground = [defaults objectForKey:@"TimeEnterBackground"]; 
NSInteger timeInBackground = [[NSDate date] timeIntervalSince1970] - [enteringBackground timeIntervalSince1970]; 

這會工作,即使應用程序將同時在後臺被關閉

+0

我知道這部分。我只需要更新標籤,當應用程序來自背景 – iOSDeveloper 2014-09-29 08:19:48

+0

現在我不明白你的probem正確。也許,在我的代碼之後,你可以從applicationWillEnterForeground調用updateCounter。 – Reconquistador 2014-09-29 08:27:42

+0

它好吧我知道了..謝謝你的回答我把它標記爲已接受 – iOSDeveloper 2014-09-29 08:33:08

2
  • 按照蘋果開發者指南es你不能做「UI更新在後臺」 你可以存儲任何變量或對象的值,當它會在mainThread上,你可以更新你的標籤
+0

是的你是對的 – iOSDeveloper 2014-09-29 08:34:28

相關問題