Search code examples
iosswiftbackgroundbackground-task

Prevent iOS from killing App after a few minutes


I'd like to prevent iOS from killing my app after a few minutes. I've read this thread here on SO: Prevent iOS from killing my app after 3 minutes . It says that if I have no backgroundtasks longer than 3 minutes my app wont be killed. Can someone verify that this is true? Because my background-task is not running longer than 3 minutes and even though my app gets killed after this time. My background-task is a timer that updates a widget. Heres some code:

self.backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
        self?.endBackgroundTask()
//endBackGroundTask looks like this
UIApplication.shared.endBackgroundTask(self.backgroundTask)
    self.backgroundTask = UIBackgroundTaskInvalid
//
    }
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self,   selector: (#selector(self.updateTimer)), userInfo: nil, repeats: true)

.

// at the beginning of the class
var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid

.

// in viewWillDisappear
self.timer.invalidate()
    if self.backgroundTask != UIBackgroundTaskInvalid {
        self.endBackgroundTask()

    }

Solution

  • You need to structure your app so that it doesn't require continual execution in the background. As I understand it, your app shows a count down timer and can show the same count down timer in a Today Widget. The approach I would use is follows:

    • Store the "end date" for the timer in user defaults to share with your widget
    • When your app is in the foreground, use a Timer to periodically update your UI
    • When your Widget is being displayed use a Timer in the widget to periodically update its UI
    • When your app moves to the background, schedule a local notification for the expiration time
    • When your app moves back to the foreground, you can cancel that scheduled notification if it hasn't yet fired.
    • Support app restoration for those cases where your app is legitimately terminated (e.g. due to memory pressure or being suspended for a long period)

    If you do this then you never need to call beginBackgroundTask. If you do call beginBackgroundTask and don't call endBackgroundTask within 3 minutes of entering the background, then your app will be terminated, even if you aren't using any CPU.