2013-08-03 4 views
1

어떤 이유에서든 내 타이머는 포 그라운드에서만 실행됩니다. 나는 여기에서 해결책을 찾았지만 어떤 좋은 것을 찾을 수 없었다. 내 타이머 코어 데이터를 사용하고 모든 timeInterval 감소 후 저장됩니다. 또한 UILocalNotification을 보내고 있지만 작동하지 않습니다.타이머를 백그라운드에서 실행 한 다음 로컬 알림을 보내려면 어떻게해야합니까?

-(IBAction)startTimer:(id)sender{ 
    if (timer == nil) { 
     [startButton setTitle:@"Pause" forState:UIControlStateNormal]; 
     timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES]; 
    } else { 
     [startButton setTitle:@"Resume" forState:UIControlStateNormal]; 
     [timer invalidate]; 
     timer = nil; 
    } 

} 
-(void)timerAction:(NSTimer *)t 
{ 
    if(testTask.timeInterval == 0) 
    { 
     if (self.timer) 
     { 
      [self timerExpired]; 
      [self.timer invalidate]; 
      self.timer = nil; 
     } 
    } 
    else 
    { 
     testTask.timeInterval--; 
     NSError *error; 
     if (![self.context save:&error]) { 
      NSLog(@"couldn't save: %@", [error localizedDescription]); 
     } 
    } 
    NSUInteger seconds = (NSUInteger)round(testTask.timeInterval); 
    NSString *string = [NSString stringWithFormat:@"%02u:%02u:%02u", 
         seconds/3600, (seconds/60) % 60, seconds % 60]; 
    timerLabel.text = string; 
    NSLog(@"%f", testTask.timeInterval); 
} 
-(void)timerExpired{ 
    UILocalNotification* localNotification = [[UILocalNotification alloc] init]; 
    localNotification.alertBody = @"Time is up"; 
    localNotification.alertAction = @"Ok"; 
    localNotification.timeZone = [NSTimeZone defaultTimeZone]; 
    [[UIApplication sharedApplication]presentLocalNotificationNow:localNotification]; 
} 

내가 (단지 백그라운드에서 내 타이머 작업을 만들기 위해 몇 가지 지침을 주셔서 감사합니다 정말 것이다 :이 내가 지금 무엇을 가지고 그것 foreground..Well의 경우 경고보기를 보내지 않습니다 그것을 믿고있어 애플의 타이머처럼). 나는 또한 백그라운드에서 응용 프로그램 ..

+0

가능한 [iPhone의 배경 스레드 문제] (http://stackoverflow.com/questions/7187967/problem-in-background-thread-in-iphone); 또한 [배경 및 nstimer에서 작업하는 동안 문제가] 참조 (http://stackoverflow.com/q/7190919) –

+2

귀하의 응용 프로그램이 백그라운드로 동안 타이머를 실행할 수 없습니다. 카운트 다운을 표시하려는 경우 앱이 백그라운드로 들어간 시간을 저장하고 다시 활성화 될 때 다시 표시해야합니다. 이 문제에 대한 여러 게시물이 있습니다. –

+0

그걸 시도 했니? performSelector : @selector (presentLocalNotificationNow :) withObject : localNotification afterDelay : 1.0];'여기서 1.0은 기다리고 싶은 시간 (초)입니다. – lucaslt89

답변

3

Josh Caswell이 쓴 것처럼, 앱이 백그라운드로 들어가기 전에 타이머 상태를 저장 한 다음 앱이 포 그라운드로 다시 들어 왔을 때 타이머 상태를 검색해야합니다.

UILocalNotification *localNotification = [[UILocalNotification alloc] init]; 
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 

[dateFormat setDateFormat:@"yyyyMMddHHmmss"]; 
    NSDate *when = [dateFormat dateFromString:desiredTime]; 
// desiredTime -> time you want your local notification to be fired, take this from your timer before app enters the background 

[dateFormat release]; 

localNotification.fireDate = when; 
localNotification.timeZone = [NSTimeZone defaultTimeZone]; 
localNotification.soundName = UILocalNotificationDefaultSoundName; 

localNotification.alertBody = @"Hey"; 

[[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; 

[localNotification release]; 

편집 : 당신이 바로 그 순간에 로컬 알림을 전송해야하는 경우

당신은 당신의 타이머의 상태를 사용하여 배경에 들어가기 전에 이런 식으로 설정할 수 있습니다 이러한 방법을 찾아야한다 AppDelegate에에서 :

(1) - (void)applicationWillResignActive:(UIApplication *)application 
(2) - (void)applicationDidEnterBackground:(UIApplication *)application 
(3) - (void)applicationWillEnterForeground:(UIApplication *)application 
(4) - (void)applicationDidBecomeActive:(UIApplication *)application 
(5) - (void)applicationWillTerminate:(UIApplication *)application 

상태가 변경 될 때 앱의 동작을 관리하기 위해 특별히 구현됩니다.

배경을 입력하기 전에 그리고 다시 시작할 때 필요한 모든 작업을 수행 할 수 있습니다.

배경을 입력하기 전에 로컬 알림 일정을 수행하고 타이머 상태를 저장하는 데 몇 초가 걸릴 수 있습니다 (예 : NSUserDefaults 사용).

더 실행 시간이 필요한 작업의 경우 장기 실행 배경 작업을 구현 : 그것은 이러한 이유 중 하나 백그라운드에서 작동하지 않는 경우에 그 애플이 아마 앱을 죽일 후

구현하려면 백그라운드에서 실행 중지하지 않고 에 특정 사용 권한을 요청해야합니다. 백그라운드에서 사용자를 유지 같은 음악 플레이어 응용 프로그램으로
  • 앱 연락하면서 사용자에게 청각 적 콘텐츠를 재생

    • 애플 리케이션 : 아이폰 OS에서 만 특정 응용 프로그램 유형은 백그라운드에서 실행할 수 있습니다 이러한 탐색 응용 프로그램으로 항상, 그들의 위치의 새로운 콘텐츠를 실외에서 정기적으로 업데이트를받을
    • 앱을 다운로드하고 처리 할 필요가 인터넷 프로토콜 (VoIP)를
    • 뉴스 가판대 앱을 통해 음성을 지원
    • 앱 리터 액세서리
  • here에서 촬영.

    백그라운드 작업에 대해 this을 읽어 보시기 바랍니다.

    +0

    배경을 입력하기 전에 일정을 잡으려면 어디에서 구현합니까? – EvilAegis

    +0

    내 편집을보세요! – Beppe

    6
    UIBackgroundTaskIdentifier bgTask =0; 
    UIApplication *app = [UIApplication sharedApplication]; 
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
        [app endBackgroundTask:bgTask]; 
    }]; 
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 
          target:self 
          selector:@selector(timerCountDown:) 
          userInfo:nil 
          repeats:YES]; 
    

    지금 알림을 발사하기 위해이 방법을 사용하는 경우에도 testTask.timeInterval 업데이트해야하기 때문에 내가 NSDateComponents을 사용하는 방법을 모르겠어요. 타이머는 백그라운드에서 실행됩니다.

    +0

    어떻게 신속하게이 작업을 수행 할 수 있습니까? – jammyman34

    관련 문제