iosapplication-lifecycleuibackgroundtask

App not suspending after long-running background task completes


Why doesn't my app suspend immediately after my long-running background task completes?

An app running on iOS 8 uses a long-running background task to avoid being suspended when it enters the background. All is well. When the task is complete, the app invokes the background task completion handler:

        [[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
        backgroundTask = UIBackgroundTaskInvalid;

However, a call to backgroundTimeRemaining returns a 40 second time interval.

[[UIApplication sharedApplication] backgroundTimeRemaining]

Indeed, the app doesn't suspend for at least another 20 seconds after ending the task.


Solution

  • After debugging further, it's become clear that backgroundTimeRemaining is not updated immediately upon task completion. The app suspends shortly afterwards, likely after a run loop spin. You should not expect backgroundTimeRemaining to be accurate at all times.