2014-11-11 3 views
1

앱이 백그라운드로 실행되면 데이터를 저장하고 싶습니다. NSOperation을 취소하고 데이터를 applicationDidEnterBackground에 저장하려고합니다. 그러나 실행을 완료하지는 않습니다.applicationDidEnterBackground가 메서드 실행이 완료 될 때까지 대기하지 않습니다.

내 앱이 백그라운드로 들어가기 전에 어떻게해야합니까?

코드 :

-(void)applicationDidEnterBackground:(UIApplication *)application 

{ 

    //FUNCTION_START 
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 

    [self performSelectorOnMainThread:@selector(dispatchStateNotification:) 
          withObject:[NSNumber numberWithInt:666] 
         waitUntilDone:YES ]; 

    // Write to core data 
    GWSCoreDataController *dataController = [GWSCoreDataController sharedManager]; 

    NSError *error; 
    if (![dataController.managedObjectContext save:&error]) { 
     NSLog(@"Error while saving data to Core Data: %@", [error localizedDescription]); 
    } 

    // FUNCTION_END 

} 

-(void)dispatchStateNotification:(NSNumber *)value { 
    [[NSNotificationCenter defaultCenter] postNotificationName:APPLICATION_ENTERED_BACKGROUND_NOTIFICATION object:value]; 

} 
+0

일부 코드를 공유하십시오. – Kampai

답변

0

아래 나와 같은 요구 사항에 대해이 문제를 해결했습니다. 이 플래그가 false가되지 않을 때까지 하나의 플래그를 추가하고 while 루프를 실행합니다. 내 작업이 완료되거나 앱이 포 그라운드로 오자 마자이 플래그를 false로 표시했습니다.

 // start the task asynchronously which is written into the block on new thread. 
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{ 

    //this loop runs continuously while flag is YES. 
    while(appDidEnterBackground){ 
     sleep(1); 
    }//end of while 

    //ends the background task. 
    [application endBackgroundTask: background_task]; 
    background_task = UIBackgroundTaskInvalid; 

});//end of dispatch queue 
0

당신은 배경 작업을 시작할 수 있으며,

- (void)applicationDidEnterBackground 
{ 
    UIBackgroundTaskIdentifier bgTaskId = 
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ 
     [[UIApplication sharedApplication] endBackgroundTask:bgTaskId]; 
    }]; 

    // Start cleanup 
    ....... 
    [[UIApplication sharedApplication] endBackgroundTask: bgTaskId]; 
} 
0

하여 정리 물건을 수행 저도 같은 문제를 가지고 대신 applicationWillResignActive에 전화 저장을 넣어했다 - didEnterBackground 단지 와 함께 저장할 수있는 전체 CoreData가없는 것 같습니다 ...