Reputation: 21
I have an app that takes the time and time interval from a user and starts to count down at that time. when I try to start the timer at the time that I have, it freaks out and not working.
this is the func that runs the timer:
func runTimer(){
let timer = Timer(fireAt: firstMealTime, interval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: .commonModes)
}
and this is the updateTimer
func:
if seconds < 1 {
timerRepeat! -= 1
updateMealLeftLabel(numberOfMeal: timerRepeat)
resetTimer()
}else{
seconds -= 1
updateTimerLabel()
}
thanks in advance!
Upvotes: 2
Views: 2240
Reputation: 2800
You can check your timer definition like this:
var seconds = YourCountdownValue // (in seconds) for example 100 seconds.
func runTimer(){
firstMealTime = Date().addingTimeInterval(10.0) // This line is for testing. Countdown will be start in 10 seconds.
let timer = Timer(fireAt: firstMealTime, interval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: .commonModes)
}
func updateTimer() {
if seconds < 1 {
timerRepeat! -= 1
updateMealLeftLabel(numberOfMeal: timerRepeat)
print("finished") //for testing
resetTimer()
}else{
seconds -= 1
print(seconds) //for testing
updateTimerLabel()
}
}
Upvotes: 1