I have a timer that runs in viewDidLoad
_ = Timer.scheduledTimer(timeInterval: 10,
target: self,
selector: #selector(timerFired),
userInfo: nil,
repeats: true)
The timer works fine, the issue is because viewDidLoad is called multiple times, the timer is duplicated.
Is there any way to ensure that my timer is only ever running once?
You need to keep a reference to your timer so you can invalidate it when your viewController disappears. Otherwise it will just keep running and new timers will be spawned every time another viewController is created.
var timer:Timer?
override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 1,
target: self,
selector: #selector(timerFired),
userInfo: nil,
repeats: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if let timer = timer {
timer.invalidate()
}
}
Depending on your navigation logic viewWillDisappear
may get called multiple times before the view is deallocated, you'll have to decide the best way to handle this yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With