Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 - How to make timer work in background

Tags:

ios

swift

timer

i am trying to do an application which can make a timer run in background.

here's my code:

let taskManager = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.scheduleNotification), userInfo: nil, repeats: true)         RunLoop.main.add(taskManager, forMode: RunLoopMode.commonModes) 

above code will perform a function that will invoke a local notification. this works when the app is in foreground, how can i make it work in the background?

i tried to put several print lines and i saw that when i minimize (pressed the home button) the app, the timer stops, when i go back to the app, it resumes.

i wanted the timer to still run in the background. is there a way to do it?

here's what i want to happen:

run app -> wait 10 secs -> notification received -> wait 10 secs -> notification received -> and back to wait and received again

that happens when in foreground. but not in background. pls help.

like image 922
Cristina Reyes Avatar asked Feb 18 '17 18:02

Cristina Reyes


People also ask

Does NSTimer run in background?

Problem is, NSTimer requires an active run loop which is not always readily available on background queues. The main thread has an active run loop but this defeats the purpose of having our timer run in the background so its a definite no go. So, to get a dedicated background-queue-friendly timer, we use GCD.

How do I make a countdown timer in Swift?

Creating a non-repeating timerlet timer1 = Timer. scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: false) let timer2 = Timer. scheduledTimer(withTimeInterval: 1.0, repeats: false) { timer in print("Timer fired!") }


2 Answers

you can go to Capabilities and turn on background mode and active Audio. AirPlay, and picture and picture.

It really works . you don't need to set DispatchQueue . you can use of Timer.

Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (t) in     print("time") } 
like image 142
2 revs Avatar answered Oct 01 '22 19:10

2 revs


A timer can run in the background only if both the following are true:

  • Your app for some other reason runs in the background. (Most apps don't; most apps are suspended when they go into the background.) And:

  • The timer was running already when the app went into the background.

like image 37
matt Avatar answered Oct 01 '22 19:10

matt