Search code examples
iosswifttimer

What lifecycle method is called when app is terminated by system in the background?


I have the following function which is activated when a silent push notification arrives in the app:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        var runCount = 0
        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
            runCount += 1
            self.writeStepInDb(function: "Timer-\(runCount)")
        }
    }

When this function runs we expect that the app is suspended (by user or system doesn't matter). The line self.writeStepInDb(function: "Timer-\(runCount)") is essentially my way of seeing that the Timer is indeed running in the background, since I have no way of reading logs when app is woken up and run in the background, instead I just have the timer constantly write to a DB and that's how I know it's running.

At the current moment, based on DB entries, I see that it will run for about ~30 seconds and then will get killed.

Does anyone know what lifecycle method is called when the app is killed after such a situation? I want to be able to start up another background task before the app is killed and thus prolong it's life some more, but I need to know right before it is about to be killed.

My main goal is to prolong the app's life in the background state (awakened by silent push notification) for as long as possible.

Once again, what is the lifecycle method called when the timer dies?


Solution

  • Thanks. From what I can tell, it seems that for certain terminations, like mine, there is no lifecycle method called for termination.

    This is because background task duration extension is frowned upon by the system and so it seems the system will terminate such apps in a very draconian fashion lol. No lifecycle method to do last minute things, just straight up deletion.