Search code examples
iosswiftnstimer

Run timer in background


In iOS system app clock, when I start a timer or stopwatch, quit the app, kill, and reopen it, the timer or stopwatch is still running.

How can I have a timer running in the background?
And how did Apple do it?


Solution

  • It's possible through a token that identifies a request to run in the background.
    Like this: var bgTask = UIBackgroundTaskIdentifier()

    Here is how to use it:

    var bgTask = UIBackgroundTaskIdentifier()
        bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
            UIApplication.shared.endBackgroundTask(bgTask)
        })
        let timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(notificationReceived), userInfo: nil, repeats: true)
        RunLoop.current.add(timer, forMode: RunLoopMode.defaultRunLoopMode)
    

    I hope it would be useful!