I’m trying to figure out a way to create a countdown timer in Swift that I can pause, stop and resume.
This is my code:
@objc func updateTimer() {
if secondsPassed < totalTime {
secondsPassed += 1
progressBar.progress = Float(secondsPassed) / Float(totalTime)
let minutes = String(totalTime / 60)
let seconds = String(totalTime % 60)
countDownLabel.text = minutes + ":" + seconds
totalTime -= 1
} else {
timer.invalidate()
titleLabel.text = "Done!"
let url = Bundle.main.url(forResource: "alarm_sound", withExtension: "mp3")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}
}
I already have a progress bar, but I can’t set up the countdown timer properly. When I run this code, I get 0:3 instead of 0:03. Another problem is that it doesn’t stop at 0:00. It just freezes before that.
Here’s the entire code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var titleLabel: UILabel!
// testando countdownlabel
@IBOutlet weak var countDownLabel: UILabel!
let eggTimes = ["Soft": 3, "Medium": 4, "Hard": 5]
var totalTime = 0
var player: AVAudioPlayer!
var secondsPassed = 0
var timer = Timer()
@IBAction func hardnessSelected(_ sender: UIButton) {
timer.invalidate()
let hardness = sender.currentTitle!
totalTime = eggTimes[hardness]!
progressBar.progress = 0.0
secondsPassed = 0
titleLabel.text = hardness
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}
@objc func updateTimer() {
if secondsPassed < totalTime {
secondsPassed += 1
progressBar.progress = Float(secondsPassed) / Float(totalTime)
let minutes = String(totalTime / 60)
let seconds = String(totalTime % 60)
countDownLabel.text = minutes + ":" + seconds
totalTime -= 1
} else {
timer.invalidate()
titleLabel.text = "Done!"
let url = Bundle.main.url(forResource: "alarm_sound", withExtension: "mp3")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}
}
}