Reputation: 119
I'm new to Swift - trying to build an app for iPhone/iPad. Hope you can help me.
I want to include a timer that counts down from 04:00 minutes to 00:00. It should then stop at zero and trigger a sound effect (which I haven't tried to implement yet). The countdown starts when you push a start button (in my code startTimer and stopTimer refer to the same button; however, the button is only pushed once at the beginning).
The timer starts and counts down just fine. It converts seconds into minutes as planned. However, my main problem is that I cannot get the countdown to stop at zero. It continues beyond as 00:0-1 etc. How do I fix this?
import Foundation
import UIKit
import AVFoundation
class Finale : UIViewController {
@IBOutlet weak var timerLabel: UILabel!
var timer = NSTimer()
var count = 240
var timerRunning = false
override func viewDidLoad() {
super.viewDidLoad()
}
func updateTime() {
count--
let seconds = count % 60
let minutes = (count / 60) % 60
let hours = count / 3600
let strHours = hours > 9 ? String(hours) : "0" + String(hours)
let strMinutes = minutes > 9 ? String(minutes) : "0" + String(minutes)
let strSeconds = seconds > 9 ? String(seconds) : "0" + String(seconds)
if hours > 0 {
timerLabel.text = "\(strHours):\(strMinutes):\(strSeconds)"
}
else {
timerLabel.text = "\(strMinutes):\(strSeconds)"
}
}
@IBAction func startTimer(sender: AnyObject) {
var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
}
func stopTimer() {
if count == 0 {
timer.invalidate()
timerRunning = false
}
}
@IBAction func stopTimer(sender: AnyObject) {
timerRunning = false
if count == 0 {
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("stopTimer"), userInfo: nil, repeats: true)
timerRunning = true
}}
}
Upvotes: 0
Views: 2326
Reputation: 119
Yay! It's working!! I used a mix of the two answers. I added stopTimer() to my updateTimer function, I deleted the "var" from the timer, and I deleted the last paragraph/IBAction of my code. Thank you so much guys! Now I'll try adding sound. :)
Upvotes: 0
Reputation: 5554
Remember, your timer doesn't count down to zero - you implement that in your code. The timer just fires every second.
In your updateTime function, you need to invalidate the timer, and call your sound function, when the timer runs out
Upvotes: 1
Reputation: 8782
func updateTime() {
count--
let seconds = count % 60
let minutes = (count / 60) % 60
let hours = count / 3600
let strHours = hours > 9 ? String(hours) : "0" + String(hours)
let strMinutes = minutes > 9 ? String(minutes) : "0" + String(minutes)
let strSeconds = seconds > 9 ? String(seconds) : "0" + String(seconds)
if hours > 0 {
timerLabel.text = "\(strHours):\(strMinutes):\(strSeconds)"
}
else {
timerLabel.text = "\(strMinutes):\(strSeconds)"
}
stopTimer()
}
Upvotes: 2