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.
I have solved this problem from this:
How to make NSTimer for multiple different controllers? In swift
3
Answers
you can add notification observer to your viewcontroller and notify once you hit on logout action.
If you just have those three view controllers you can set the Timer like a Singleton, so you can access to them in any part of your code and also you can enable and disable as you need.
So you can use the function .invalidate() to stop it