2014-09-29 6 views
0

NSTimer가 백그라운드에서 작동하지 않는다는 것을 알게되었습니다. 내 애플 리케이션은 백그라운드에서 타이머를 실행하도록 요구합니다. 내가 무엇을하기로 결정 한 것은앱이 백그라운드로 들어가는 시간과 앱이 백그라운드로 들어가는 시간을 계산합니다. 앱이 포 그라운드로 들어갔습니다.

- (void)applicationWillEnterForeground:(UIApplication *)application 

에 앱

- (void)applicationDidEnterBackground:(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

+0

이제 probem을 제대로 이해하지 못합니다. 어쩌면, 내 코드 후, 당신은 applicationWillEnterForeground에서 updateCounter를 호출 할 수있다. – Reconquistador

+0

알았어. 알았어. 대답 해 줘서 고마워. – iOSDeveloper

2
  • 애플 개발자 가이드 라인 ES 당신이 값을 저장할 수있는 변수 또는 객체 "배경에 UI 업데이트를"할 수 없다, 그것은 mainThread에 올 때 당신은 당신의 라벨
+0

네가 맞아. – iOSDeveloper

관련 문제