2014-09-29 56 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

相关问题