Search code examples
iosswiftcountdowntimersecondsminute

How Do I create a countdown timer with minutes and seconds in swift?


I can't find a single tutorial that does countdown timer with minutes and seconds. There's one or two but they are kind of bad.

import UIKit

class HomeViewController: UIViewController {
    @IBOutlet weak var focusSession: UILabel!
    @IBOutlet weak var breakSession: UILabel!

    var prodSeconds = String() // This value is set in a different view controller
    lazy var intProdSeconds = Int(prodSeconds)
    var timer = Timer()
    var isTimerRunning = false  // Make sure only one timer is running at a time

    override func viewDidLoad() {
        super.viewDidLoad()

        if isTimerRunning == false {
            runProdTimer()
        }

        //focusSession.text = String(prodMinutes) + ":" + String(prodSeconds) // Ignore this for now stack overflow ppl
    }

    func runProdTimer() {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(HomeViewController.updateProdTimer)), userInfo: nil, repeats: true)
        isTimerRunning = true
    }

    @objc func updateProdTimer() {
        if intProdSeconds! < 1 {
            timer.invalidate()
            focusSession.text = "00:00"
        }
        else {
            intProdSeconds! -= 1
            focusSession.text = prodTimeString(time: TimeInterval(prodSeconds)!)
        }
    }

    func prodTimeString(time: TimeInterval) -> String {
        let prodMinutes = Int(time) / 60 % 60
        let prodSeconds = Int(time) % 60

        return String(format: "%02d:%02d", prodMinutes, prodSeconds)
    }
}

The user inputs their time amount and it is stored in the prodSeconds variable which is then converted to an Int below it with the lazy variable.

However, the timer still doesn't countdown when I run the app. This is supposedly just a timer for seconds which I was following from a different tutorial. But all that happens is that the label that displays the timer simply displays the number inputted by the user in the format of 00:prodSeconds and doesn't actually countdown.

P.S. Don't worry about implementing a start/stop button for now. In my case, the timer is supposed to start when the view loads.


Solution

  • The problem is that you count down from

    intProdSeconds! -= 1
    

    and pass prodSeconds to this

    focusSession.text = prodTimeString(time: TimeInterval(prodSeconds)!)
    

    so make sure to deal only with intProdSeconds