Nitesh Nitesh - 4 years ago 104
iOS Question

Deinit / Invalidate Timer

I'm trying to deinit/invalidate

Timer
when user press back button but not when he push to next ViewController.

var timer = Timer()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timePrinter), userInfo: nil, repeats: true)
timer.fire()

override func viewWillDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if self.isMovingFromParentViewController{
timer.invalidate()
}
}


It is not working when user press back button.

Answer Source

Fixed it by adding Timer() in viewDidAppear and on viewDidDisappear I'm doing timer.invalidate()

override func viewDidAppear(_ animated: Bool) {
    if setTimer == true{
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timePrinter), userInfo: nil, repeats: true)
        timer.fire()
    }
}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
        timer.invalidate()
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download