0

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

Max Kraev
  • 740
  • 12
  • 31

2 Answers2

1

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)

}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
1

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579