Alec. Alec. - 25 days ago 19
iOS Question

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?

Answer

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)
    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.

Comments