2013-03-09 2 views
0

응용 프로그램이 백그라운드 상태로 들어가면 백그라운드에서 실행하는 데 사용 된 시간이 작동하지 않습니다. 다음은 코드입니다. AppDelegate.h에서 긴 프로세스를위한 iPhone 타이머 작업

, AppDelegate.m

- (void)applicationDidEnterBackground:(UIApplication *)application 
{ 

    NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil); 

    bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{ 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      [application endBackgroundTask:self->bgTask]; 
      self->bgTask = UIBackgroundTaskInvalid; 
     }); 
    }]; 

    dispatch_async(dispatch_get_main_queue(), ^{ 

     if ([application backgroundTimeRemaining] > 1.0) { 
      // Start background service synchronously 
      [[vController getInstance] run]; 

     } 

     [application endBackgroundTask:self->bgTask]; 
     self->bgTask = UIBackgroundTaskInvalid; 

    }); 
} 

- (void)applicationWillEnterForeground:(UIApplication *)application 
{ 
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 
    NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil); 

    bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{ 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      [application endBackgroundTask:self->bgTask]; 
      self->bgTask = UIBackgroundTaskInvalid; 
     }); 
    }]; 

    dispatch_async(dispatch_get_main_queue(), ^{ 

     if ([application backgroundTimeRemaining] > 1.0) { 

      // Start background service synchronously 
      [[vController getInstance] stopbackground]; 

     } 

     [application endBackgroundTask:self->bgTask]; 
     self->bgTask = UIBackgroundTaskInvalid; 

    }); 
} 

및 도면에 Controller.h

@interface AppDelegate : UIResponder <UIApplicationDelegate> 
{ 
    BOOL status; 
    UIBackgroundTaskIdentifier bgTask; 
} 

,

@interface vController : UIViewController <AVAudioPlayerDelegate> 
-(void) run; 
-(void) stopbackground; 
-(void) getMessage:(NSTimer*)theTimer;; 
+(vController*) getInstance; 
@property (nonatomic,retain) NSTimer * timer; 
@end 

뷰 controller.m,

@implementation vController 
@synthesize timer; 
vController *tvc; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    tvc = self; 
    // Do any additional setup after loading the view, typically from a nib. 
} 

+ (vController*) getInstance 
{ 
    return tvc; 
} 

- (void)stopbackground 
{ 
    timer = [NSTimer scheduledTimerWithTimeInterval:15.0 target:self selector:@selector(getMessage:) userInfo:nil repeats:YES]; 
} 

- (void)run 
{ 
    timer = [NSTimer scheduledTimerWithTimeInterval:15.0 target:self selector:@selector(getMessage:) userInfo:nil repeats:YES]; 
} 

- (void) getMessage:(NSTimer*) theTimer 
{ 

    NSError *error; 

    NSString *path = [[NSBundle mainBundle] pathForResource:@"alert" ofType:@"mp3"]; 
    AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error]; 
    if (theAudio == nil) { 
     NSLog(@"%@", [error description]); 
    } 
    NSLog(@"Hi"); 
    theAudio.delegate = self; 
    theAudio.numberOfLoops = 1; 
    [theAudio play]; 
} 

- (void) dealloc{ 
    [timer release]; 
    [super dealloc]; 
} 

시뮬레이터 6.0에 사용 중입니다.

답변

0

사용 사례에 따라 다를 수 있습니다. 즉, 애플은 당신이 '배경'에서 코드를 실행하지 않고 다음 작업 중 하나를 수행하지 않는 : 사용자에게 청각 적 콘텐츠를 재생

  • 앱을하는 동안 백그라운드에서, 같은 음악 플레이어 응용 프로그램 인터넷 프로토콜 (VoIP)를 새로운 콘텐츠를
  • 앱을 다운로드하고 처리 할 필요가
  • 뉴스 가판대 앱을 통해 음성을 지원하는 등 내비게이션 애플리케이션으로, 항상 자신의 위치에 대한 정보를
  • 앱 사용자를 유지
  • 앱 정규 upda를받는 사람 외부 액세서리

에서 TES은 더 읽기 : 인스턴스 아래처럼 모든 뷰 컨트롤러에서 백그라운드 작업을 실행 할 수 있습니다 만들어 http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html

+0

답장을 보내 주셔서 감사합니다 ... http 통신을 통해 무언가를 다운로드하고 일정 기간에받은 데이터를 처리해야합니까 ?? – Shailesh

+0

이것은 구현 세부 사항입니다 (http를 통해 다운로드). 위의 중 어느 부분에서 앱이하고 있습니까? 음, "외부 액세스 목록에서 정기적 인 업데이트", "VoIP", "탐색 앱"이 될 수 없으며 "음악 플레이어 앱"이 아닐 것입니다. 그건 "뉴스 스탠드 앱"을 남겨두고 ... "뉴스 스탠드 앱"을 만들지 않거나 내 가정이 틀린 경우 앱을 AppStore 용으로 승인 받기를 원하면 백그라운드에서 코드를 실행해서는 안됩니다. –

+0

고맙습니다. 회신 .... 이것은 일부 서버로 가서 일정한 간격으로 http를 통해 데이터를 가져와야한다는 앱의 기본 요구 사항입니다. – Shailesh

0

을 :

는 // YourViewController.h 파일에 다음과 같이 선언합니다.

+ (YourViewController *)getInstance; 
- (void)run; 
-(void)stopbackground; 

// YourViewController.m 파일에 Vollowing을 정의하십시오. AppDelegate.h 파일

static YourViewController *instance = NULL; 

+(YourViewController *)getInstance { 

    @synchronized(self) { 
     if (instance == NULL) { 
      instance = [[self alloc] init]; 
     } 
    } 
    return instance; 
} 


- (void)run 

{ 
// strat Back ground task 
} 
-(void)stopbackground 
{ 
// Stop Background task 
} 

AppDelegate.m 파일에 다음

UIBackgroundTaskIdentifier bgTask; 

다음과 같은 방법을 사용하여 선언합니다.

- (void)applicationDidEnterBackground:(UIApplication *)application { 
    NSLog(@"Application entered background state."); 

    // bgTask is instance variable 
    NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil); 

    bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{ 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      [application endBackgroundTask:self->bgTask]; 
      self->bgTask = UIBackgroundTaskInvalid; 
     }); 
    }]; 

    dispatch_async(dispatch_get_main_queue(), ^{ 

     if ([application backgroundTimeRemaining] > 1.0) { 
      // Start background service synchronously 
[[YourViewController getInstance] run]; 

     } 

     [application endBackgroundTask:self->bgTask]; 
     self->bgTask = UIBackgroundTaskInvalid; 

    }); 
} 


- (void)applicationWillEnterForeground:(UIApplication *)application 
{ 

    NSLog(@"Application entered background state."); 

    // bgTask is instance variable 
    NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil); 

    bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{ 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      [application endBackgroundTask:self->bgTask]; 
      self->bgTask = UIBackgroundTaskInvalid; 
     }); 
    }]; 

    dispatch_async(dispatch_get_main_queue(), ^{ 

     if ([application backgroundTimeRemaining] > 1.0) { 

// Start background service synchronously 
    [[YourViewController getInstance] stopbackground]; 

     } 

     [application endBackgroundTask:self->bgTask]; 
     self->bgTask = UIBackgroundTaskInvalid; 

    }); 


    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 
} 
+0

thax 답장을 많이 ... Siba Prasad, 그것을 시도합니다 ... 고맙습니다 – Shailesh

+0

시간 및 일정한 간격으로 반복되는 작업을 실행하려면 Run 및 StopBackground 메서드에서 Timer를 사용해야합니까 ?? Pls help ... – Shailesh

+0

예 Timer with Repeat 예/아니오 –