Reputation: 491
My storyboard goes like this: MainNavViewController --> TimerViewController
The TimeViewController contains the NSTimer and the code which manages it.
The NSTimer should AUTOMATICALLY start to countdown once the TimerViewController is opened.
The timer should countdown from 02:00 minutes up to 00:00.
The timer is needed in the said ViewController only, not in the next or the one before it.
Currently, I have the code below:
var timer = NSTimer()
let timeInterval:NSTimeInterval = 0.05
let timerEnd:NSTimeInterval = 0.0
var timeCount:NSTimeInterval = 120.0
func timerDidEnd(timer:NSTimer){
timeCount = timeCount - timeInterval
if timeCount <= 0 {
TimerLabel.text = "Time's Up!"
timer.invalidate()
}
}
func timeString(time:NSTimeInterval) -> String {
let minutes = Int(time) / 60
let seconds = time - Double(minutes) * 60
return String(format:"%02i:%02i",minutes,Int(seconds))
}
func StartTimer() { // Function called in viewDidLoad
if !timer.valid{
TimerLabel.text = timeString(timeCount)
timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval,
target: self,
selector: "timerDidEnd:",
userInfo: nil,
repeats: true)
}
}
HOWEVER, the code won't work and the timerLabel is just set at 02:00 WITHOUT running (counting down).
Upvotes: 1
Views: 178
Reputation: 1087
You forgot to set the text every time the timer function is called
func timerDidEnd(timer:NSTimer){
timeCount = timeCount - timeInterval
if timeCount <= 0 {
TimerLabel.text = "Time's Up!"
timer.invalidate()
// Start edit
} else {
TimerLabel.text = timeString(timeCount)
}
// End edit
}
Upvotes: 3