Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 Timer not firing [duplicate]

Tags:

ios

swift

timer

I've been trying to utilize Timer in Swift and I've simplified it town to the following:

func startTimer () {
    timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.test), userInfo: nil, repeats: true)
}
func test () {
    print("FIRED")
}

I would like to call this from another function and have verified the startTimer function works, but the timer doesn't fire. Does this have something to do with the RunLoop? I'm fairly new to coding so any explanation would be appreciated.

like image 420
Oliver Hickman Avatar asked Dec 23 '16 19:12

Oliver Hickman


1 Answers

Good Practice: In startTimer() check that the timer has not already been created and make the assignment. In stopTimer() check that the timer exists before calling invalidate, and set the timer back to nil.

Also, for your selector make sure you have the @objc prefix. You should be able to get a working timer with the code provided. Happy coding!

class SomeClass {
    var timer: Timer?

    func startTimer() {
        guard timer == nil else { return }
        timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(test), userInfo: nil, repeats: true)
    }

    func stopTimer() {
        guard timer != nil else { return }
        timer?.invalidate()
        timer = nil
    }

    @objc func test() {

    }
}
like image 126
Alex Blair Avatar answered Oct 12 '22 23:10

Alex Blair