Home > other >  How to stop the timer in other viewcontroller?
How to stop the timer in other viewcontroller?

Time:11-02

In my case, my app have three view controller(there are loginview, homeview, menuview)

In the homeview, I set a timer reload data from the server every 10 seconds. Code as shown below:

Timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(loadData), userInfo: nil, repeats: true)


let storyBoard: UIStoryboard = UIStoryboard(name: "mapFirstPage", bundle: nil)
    let newViewController = storyBoard.instantiateViewController(withIdentifier: "menuSetupVC") as! menuSetupViewController
    newViewController.modalPresentationStyle = .fullScreen
    self.navigationController?.pushViewController(newViewController, animated: true)

And when I go to menuview, there is a logout btn, it can take me to the loginview. But the timer still running in the background...

how can I stop it when I in menuview.

CodePudding user response:

let storyBoard: UIStoryboard = UIStoryboard(name: "mapFirstPage", bundle: nil)
    let newViewController = storyBoard.instantiateViewController(withIdentifier: "menuSetupVC") as! menuSetupViewController
Timer!.invalidate()// will stop the timer
    newViewController.modalPresentationStyle = .fullScreen
    self.navigationController?.pushViewController(newViewController, animated: true)

CodePudding user response:

you can add notification observer to your viewcontroller and notify once you hit on logout action.

  • Related