skip to Main Content

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


  1. 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)
    
    Login or Signup to reply.
  2. you can add notification observer to your viewcontroller and notify once you hit on logout action.

    Login or Signup to reply.
  3. 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

    func startTimer() {
        stopTimer()
        guard self.timer == nil else { return }
        self.timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(loadData), userInfo: nil, repeats: true)
    }
    
    func stopTimer() {
        guard timer != nil else { return }
        timer?.invalidate()
        timer = nil
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search