Search code examples
swiftnstimercountdown

CountDown using NSTimer in swift


I'm still learning swift, and i'm trying to design an application and in one section i had this game timer that is set to 7 minutes ( gonna add figure out how to let the client change that later), for now it's 7:00, i have added 2 buttons, Start, Pause. and i wanted to let Start, starts the countDown until 00:00, then i was planning to add a pop up message saying time is up!.

Code so far:

import UIKit

class ViewController: UIViewController {
@IBOutlet var countDown: UILabel!

var counter = 60
var timer = NSTimer()

func update() {

    if counter > 0 {
        countDown.text = String(counter--)
    }

}

@IBAction func start(sender: UIButton) {

    timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)

}

@IBAction func pause(sender: UIButton) {
     // timer.invalidate() stops the whole thing...
}

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

}

however, the app keeps on crashing... and i don't know how to make the timer more than 60 seconds, like how to represent it.


Solution

  • This would not be the way that I would do a countdown timer.

    @IBAction func start(sender: UIButton) {
         self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.update(_:)), userInfo: nil, repeats: true)
         NSRunLoop.currentRunLoop().addTimer(self.timer, forMode: NSRunLoopCommonModes)
        startTime = NSDate() // new instance variable that you would need to add.
    }
    
    func update() {
        let elapsedTime = NSDate().timeIntervalSinceDate(startTime)
        let currTime = totalTime - elapsedTime 
        //total time is an instance variable that is the total amount of time in seconds that you want
        countDown.text = String(currTime)
        if currTime < 0 {
            timer.invalidate()
            //do other stuff that you need to do when time runs out.
        }
    }
    

    Also make sure that your IBAction outlets are right in interface builder.