0

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

[myUser saveInBackground:^(BOOL success){
    if(success){
        // Do smthing
    }
    else{
        // 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 ?

Thanks

John smith
  • 355
  • 4
  • 17

1 Answers1

1

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.

Oleg
  • 488
  • 4
  • 14
  • Well I think this is exactly what I need. Just one question, when shoud I call [application endBackgroundTask:bgTask]; ? Because when wrote "// Save your data", did you mean that the save was synchronous ? Because my save methode is asynchronous and then should I call endBackgroundTask when my completion block is called or just after the call to my save method ? – John smith Sep 29 '16 at 12:31
  • You should call [application endBackgroundTask:bgTask]; method when your saving is finished. It notifies the iOS about finished task. And it's just an example of performing the task. You are free to call it synchronously or asynchronously. – Oleg Sep 29 '16 at 12:49
  • Well ok. But let's say my saving lasts 10sec, then everything that happens after the save is also executed in the backgroundtask ? How can I say I just want the save to be execute in the background task ? – John smith Sep 29 '16 at 13:18
  • "everything that happens after the save is also executed in the backgroundtask" Until you call `[application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid;`. Take a look at [the first anwer here](http://stackoverflow.com/questions/12071726/how-to-use-beginbackgroundtaskwithexpirationhandler-for-already-running-task-in). It explains a lot. – Oleg Sep 29 '16 at 15:49