Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run timer in background

Tags:

ios

swift

nstimer

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?

like image 406
FaiChou Avatar asked Dec 18 '22 07:12

FaiChou


1 Answers

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!

like image 59
Gabs Avatar answered Jan 04 '23 16:01

Gabs