Search code examples
iosswiftnstimer

All digits not shown in timer countdown


While coming to a view I call a function to load a timer like so...

var count = 10

 func startTimer() {
         timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
  }

and update function is given as..

@objc func update() {
    while (count != 0) {
      count -= 1
      countdownLabel.text = "\(count)"

    }
     timer.invalidate()
  }

But what happens is when I come to this view, straightaway the number 0 is shown as opposed to ideally displaying all numbers in the sequence 9,8,7,6,5,4,3,2,1,0

What am I doing wrong here..?


Solution

  • Swift 4:

        var totalTime = 10
        var countdownTimer: Timer!
    
        @IBOutlet weak var timeLabel: UILabel!
    
        override func viewDidLoad() {
          super.viewDidLoad()
          startTimer()
        }
    

    This method call initializes the timer. It specifies the timeInterval (how often the a method will be called) and the selector (the method being called).

    The interval is measured seconds so for it to perform like a standard clock we should set this argument to 1.

        func startTimer() {
             countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
        }
    
    // Stops the timer from ever firing again and requests its removal from its run loop.
       func endTimer() {
           countdownTimer.invalidate()
       }
    
      //updateTimer is the name of the method that will be called at each second. This method will update the label
       @objc func updateTime() {
          timeLabel.text = "\(totalTime)"
    
           if totalTime != 0 {
              totalTime -= 1
           } else {
              endTimer()
           }
       }