John smith John smith - 10 months ago 65
Objective-C Question

Objective c - Save completion block when app enter in background

In my application, the user needs to save some information to my database.

[myUser saveInBackground:^(BOOL success){
// Do smthing
// Alert the user

For now it's working fine and when something wrong happenned during the save I'm able to alert the user only if the application is still open and active.

Let's say that the request to my database lasts about 10 sec (bad network for instance) and the user decides to leave the app, my completion block doesn't get fired.

How can I alert the user that the save failed when he has already left the app ?


Answer Source

Take a look at Background Modes. This example is taken from the mentioned documentation:

- (void)yourSavingMethod {
    UIApplication *application = [UIApplication sharedApplication];
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        // Unfortunately, timeout..
        // Clean up any unfinished task.

        // stopped or ending the task outright.
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;

    // Start the long-running task and return immediately. 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // Save your data.

        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;

You can call -beginBackgroundTaskWithExpirationHandler: when you really need it. But don't forget to end a task. Explore documentation for more details.