Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIApplication.shared.beginBackgroundTask is not working on iOS 13

Tags:

ios13

swift4.2

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
}
like image 324
Lubaba Hasnain Avatar asked Oct 07 '19 08:10

Lubaba Hasnain


People also ask

What long running tasks can iOS support in the background?

The answer is simply 600 seconds (10 minutes), reason is provided by the article above.

How long will an iOS app run in the background?

Tasks are under a strict time limit, and typically get about 600 seconds (10 minutes) of processing time after an application has moved to the background on iOS 6, and less than 10 minutes on iOS 7+.

What is background fetch in iOS?

Background fetch is a new mode that lets your app appear always up-to-date with the latest information while minimizing the impact on battery. You could download feeds within fixed time intervals with this capability. To get started: 1- Check Background Fetch in capabilities screen in Xcode.


1 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

like image 156
K.R. Avatar answered Sep 27 '22 23:09

K.R.