Search code examples
iosswifttimernstimer

How to invalidate timer outside ViewDidLoad


I'm stuck with invalidating timer outside of ViewDidLoad. Tried to declare timer globally, but got a SIGABRT error. What am am I missing?

override func viewDidAppear(_ animated: Bool) {

    let timer = Timer(timeInterval: 3, 
                      target: self, 
                      selector: #selector(updateOnlineTrack), 
                      userInfo: nil, 
                      repeats: true)

    RunLoop.current.add(timer, forMode: .defaultRunLoopMode)
    timer.fire()

}

updateOnlineTrack is marked with @objc and project is compiling, but I can't figure out this SIGABRT

@objc private func updateOnlineTrack() {

    print("Tick")

}

Basically I need to invalidate timer and stop updating, when user leaves current View Controller.

Any help is appreciated


Solution

  • You need to declare timer as an instance property instead of a local variable.

    class MyViewController: UIViewController {
        var timer: Timer?
    
        override func viewDidAppear(_ animated: Bool) {
            timer = Timer.scheduledTimer(timeInterval: 3, 
                      target: self, 
                      selector: #selector(updateOnlineTrack), 
                      userInfo: nil, 
                      repeats: true)
    
            timer?.fire()
        }
    }
    

    Note that it is optional.

    Note the use of scheduledTimer. This is simpler than adding it to a runloop yourself.