prikkles
prikkles

Reputation: 103

How do I get NSTimer to restart updating a label when returning to a ViewController?

I have a basic Timer app (the start of something a bit more complex) and I'm trying to allow the user to open a new view, change some settings, then return to the time screen and have the timer still ticking down.

At the moment, when the user returns to the timer screen ViewController, my timer is still firing and printing the time to the console, but the label has stopped updating.

How do I start the timer updating the label again?

class Countdown 
{
    var initial = 100
    var count = 100
    var timer: NSTimer!
    var timerRunning = false
}

var globals = Countdown()

class ViewController: UIViewController {

@IBOutlet weak var timer1Label: UILabel!

@IBAction func unwindSegue(sender: UIStoryboardSegue) {} // Added to get rewind segue to work as recommended by Ben Sullivan

@IBAction func timer1(sender: AnyObject) 
{
    globals.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.timerRunning), userInfo: nil, repeats: true)
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

func timerRunning()
{
    globals.timerRunning = true
    let minutes = (globals.count / 60) % 60;
    let seconds = globals.count % 60
    print("\(minutes):\(seconds)")
    globals.count = globals.count - 1
    timer1Label.text = String("\(minutes):\(seconds)")
} 

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

At the moment, the settings view controller has nothing on it - just a button that returns the user to ViewController.

Upvotes: 1

Views: 92

Answers (1)

Ben Sullivan
Ben Sullivan

Reputation: 2154

The issue is that you are performing new segue to your timer view controller. This creates a new instance of your timer view controller rather than segueing back to the original one.

First delete the segue you have setup from your second to first controller. You will then need to use an unwind segue, you can learn how to do this by following the link below. (I had the same issue as yourself recently and this is what I was provided also)

https://developer.apple.com/library/ios/technotes/tn2298/_index.html

By using the unwind segue you shouldn't need to add any additional code as the label on your original controller should still be getting updated.

Upvotes: 1

Related Questions