Max Kraev
Max Kraev

Reputation: 770

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

Upvotes: 0

Views: 329

Answers (2)

rmaddy
rmaddy

Reputation: 318774

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.

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

The timer is fired automatically when you init it after the specified interval , you can declare it like this

var timer:timer?

//

override func viewDidAppear(_ animated: Bool) {

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

}

Upvotes: 1

Related Questions