Search code examples
swiftnstimer

How do I use NSTimer to countdown from 10 seconds then stop the timer?


This is what I have so far.

 @IBOutlet weak var countLabel1: UILabel!
 @IBOutlet weak var start: UIButton!

 var count = 10

 override func viewDidLoad() {
    super.viewDidLoad()
    var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self.start, selector: Selector("update"), userInfo: nil, repeats: true)
 }

 func update() {
    if(count > 0) {
        countLabel1.text = String(count--)
    } 
 }

 func timerFinished(timer: NSTimer) {
    timer.invalidate()
 }

Solution

  • Define the timer as a var in your class:

    var timer = NSTimer()
    

    Create the timer in viewDidLoad:

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

    Update than will be called every 0.4 second (more or less):

    func update() {
    
    if(count > 0)
    {
        countLabel1.text = String(count--)
    } else {
     timer.invalidate()
    }}
    

    Edit: [If you want to get update called every second put 1 instead of 0.4 of course.]