Search code examples
iosswiftuinavigationcontrollerviewcontrollerback-button

How to preserve a Timer instance


I have a view controller (TimerVC) in which I run a timer and I am showing the current state of the timer in a label.

My timer function:

func runTimer() {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(updateTimer)), userInfo: nil, repeats: true)
}

After user taps "Back" button on the navigation bar when TimerVC is open (step 1), when the user taps a button to show TimerVC again (step 2), I can see in the console that timer is still running in the background but its state is not being updated in the label.

I guess that this is because TimerVC's current instance is destroyed when user press "Back" button, and when the user opens TimerVC again, it creates a new instance of TimerVC, thus the label cannot be updated.

I have no idea how I can preserve my TimerVC instance when the user taps on the back button in Navigation Bar and restore that old TimerVC instance when the user triggers a segue to TimerVC.

To solve this problem at step 2, I tried to go back in the navigation stack instead of creating a new push segue to the TimerVC, but it did not work, probably because old TimerVC view controller could not be found in the stack, so it could not be restored. This is not surprising, it should have probably been destroyed when the back button was tapped.

What should I do to solve this problem?


Solution

  • In the view controller which is before the TimerVC have a property

     var timerVC = TimerVC()
    

    when you need to show it just push it

    self.navigationController.pushViewController(self.timerVC, animated:true)
    

    This way you will always be dealing with the same instance of TimerVC