Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer.scheduledTimer does not work in Swift 3

I want to call the method func adjustmentBestSongBpmHeartRate() every 1.1 second. I used Timer, but it doesn't work. I have read the document and found a lot of sample code, it still does work! Is there anything I missed?

timer = Timer.scheduledTimer(timeInterval: 1.1, target: self, selector: #selector(self.adjustmentBestSongBpmHeartRate), userInfo: nil, repeats: false) timer.fire()  func adjustmentBestSongBpmHeartRate() {     print("frr") } 
like image 633
Jing Bian Avatar asked Nov 15 '16 15:11

Jing Bian


People also ask

How do you call a timer in Swift?

A Basic timer is declared as such: //declare blank timer variable var timer = Timer() //in a function or viewDidLoad() timer = Timer. scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true) //new function @objc func timerAction(){ print(“timer fired!”) }

What is selector in timer Swift?

selector() is where you'd add in the function that you want it to call every timeInterval you set. In your example it's every second. Do bare in mind that in Swift 4 and above, you need to add @objc before a function if you want to call it in a selector like so: @objc func handleEverySecond() { print("Hello world!")


1 Answers

I found that creating the timer in an OperationQueue Operation did not work. I assume this is because there is no runloop.

Therefore, the following code fixed my problem:

DispatchQueue.main.async {     // timer needs a runloop?     self.timeoutTimer = Timer.scheduledTimer(timeInterval: self.timeout, target: self, selector: #selector(self.onTimeout(_:)), userInfo: nil, repeats: false) } 
like image 157
Nick Hingston Avatar answered Sep 20 '22 20:09

Nick Hingston