1

I have the following,

class someViewController : ViewController{
    var timer:Timer? = nil

    override func viewDidLoad() {
        timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(fire), userInfo: nil, repeats: true)

}

@objc func fire(){
print("fired")
}
    
}

The fire function is never hit and I can't figure out why, what am I missing?

Alec.
  • 5,371
  • 5
  • 34
  • 69
  • Nothing is missing what I can see, have you debugged the code? – Joakim Danielson Feb 05 '21 at 14:08
  • Yeah it's definitely hitting the create timer part, gets past that fine and then just doesn't drop into the fire function, so weird. – Alec. Feb 05 '21 at 14:16
  • not related to your question but you dont need to declare your timer as optional `var timer: Timer = .init()` – Leo Dabus Feb 05 '21 at 14:37
  • 1
    dont forget to call `super.viewDidLoad()` – Leo Dabus Feb 05 '21 at 14:37
  • I know that's just the state it was in after I was trying everything under the sun. Something weird going on as running it through DispatchQueue.main is fine. – Alec. Feb 05 '21 at 14:38
  • Did you ever resolve this issue? If so, what did you do? I am having the same issue as I too have a second view controller and I setup a timer and it never fires. I have added code that ensures the timer is being run on the main thread, but still no firing of the timer. – SouthernYankee65 Jan 25 '22 at 02:12

1 Answers1

0

Here is the issue: the timer needs to be scheduled on main thread:

DispatchQueue.main.async {  
let timer = Timer.scheduledTimer(timeInterval: self.BLINK_TIMEOUT, target: self, selector: #selector(self.clearTimer), userInfo: nil, repeats: false)

}

Hope it helps!

us_david
  • 4,431
  • 35
  • 29