【问题标题】:applicationDidEnterBackground is not waiting till method execution is completedapplicationDidEnterBackground 不等到方法执行完成
【发布时间】:2014-11-11 06:14:20
【问题描述】:

我想在应用程序进入后台时保存数据。我正在取消 NSOperation 并将数据保存在 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];

}

【问题讨论】:

    标签: ios iphone nsnotificationcenter nsoperation appdelegate


    【解决方案1】:

    您可以启动后台任务,然后进行清理工作

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

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,不得不将保存调用放在 applicationWillResignActive 中 - didEnterBackground 似乎没有完整的 CoreData 来保存...

      【讨论】:

        【解决方案3】:

        我已经为我的要求解决了这个问题,如下所示。添加一个标志并运行while循环,直到该标志不会变为假。一旦我的任务完成或应用程序进入前台,我已将此标志标记为假。

             // 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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-04-05
          • 2013-09-01
          • 2020-03-11
          • 1970-01-01
          • 1970-01-01
          • 2012-07-07
          • 2014-11-25
          • 2020-12-07
          相关资源
          最近更新 更多