Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Prevent timer duplicating

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?

like image 599
Alec. Avatar asked Feb 05 '23 17:02

Alec.


1 Answers

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.

like image 199
James P Avatar answered Feb 20 '23 15:02

James P