selytch
selytch

Reputation: 535

ios background tasks - explain sequence of execution?

Could someone explain sequence of execution please in applicationDidEnterBackground?

UIBackgroundTaskIdentifier background_task;
background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {

    [application endBackgroundTask: background_task]; 
    background_task = UIBackgroundTaskInvalid; 
}];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSLog(@"\n\nRunning in the background!\n\n");
    [application endBackgroundTask: background_task]; 
    background_task = UIBackgroundTaskInvalid; 
});

My understanding is

  1. create identifier for background task and assign block that will be called once time (10 minutes or so) expires
  2. dispatch async method, output NSLog. During this time all other methods of the app can be used
  3. immediately after NSLog out terminate background task, not waiting for system default expiration

Specifically, after I call NSLog

[application endBackgroundTask: background_task]; 
background_task = UIBackgroundTaskInvalid; 

task will be terminated and expirationHandler block will not be called.

I also think my understanding is incorrect...

Upvotes: 0

Views: 277

Answers (1)

rmaddy
rmaddy

Reputation: 318794

Everything about your post is basically correct except for one important detail. None of this has anything to do with the applicationDidEnterBackground app delegate method.

Any task in your app that might take more than a couple of seconds should be wrapped inside calls to beginBackgroundTaskWithExpirationHandler and endBackgroundTask.

The whole point of wrapping code in these two methods is to notify the OS that you have some processing that needs to keep running even if the app happens to enter the background while it is running. Without these blocks, your app will be killed by the OS after only a few (10?) seconds of trying to run in the background.

Upvotes: 2

Related Questions