UIApplication.shared.beginBackgroundTask is not working on iOS 13

Viewed 3150

UIApplication.shared.beginBackgroundTask is not working on iOS 13. Is there any alternative to implement long running background tasks on iOS 13? Also, it works perfectly on iOS 12 and below versions.

When the app goes background, it is getting terminated within 2 minutes whereas I want it to continue for hours in the background as we are doing some processing in the background.

Below is the code that I am using so that when my app is in background, it can get extra execution time. We need that extra execution time because we are sending the current location to the server on periodic intervals.

/// Register background task. This method requests additional background execution time for the app
private func registerBackgroundTask() {
    DispatchQueue.global().async {
        self.backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "BgTask", expirationHandler: {
            // Ends long-running background task
            self.endBackgroundTask()
        })
    }
}

/// Ends long-running background task. Called when app comes to foreground from background
private func endBackgroundTask() {
    UIApplication.shared.endBackgroundTask(backgroundTask)
    backgroundTask = UIBackgroundTaskInvalid
}
2 Answers

It is working perfectly fine. By definition, it should extend your app's background execution time by several minutes in order for you to complete already started tasks, that might be detrimental for your app if not properly finished. Used to be 10 minutes, now it is 3 minutes. Actually I think it is down to 30 seconds, judging by the latest articles I find online

So this is absolutely not the right tool for your needs. Try looking into URLSessionConfiguration.background(withIdentifier:) but beware, because there are many risks and some bugs around it.

Also, do an internet search for Dropbox background location updates to see how Dropbox are working around background limitations.

Best of luck

For general counsel about background tasks in iOS 13, see WWDC 2019 Advances in App Background Execution. But the short answer is that you cannot just keep the app running indefinitely in the background. Apple has done this to ensure that apps don’t kill the user’s battery.

If you want to be “sending the current location to the server on periodic intervals”, I’d suggest checking out the significant change location service or the visits location service. With these services, the OS can wake your app if there is a material change in the user’s location.

See Handling Location Events in the Background, too.

Related