Hey I've been trying to create an accurate timer in Swift for a while now. I started with timer.shedueld to call up a closure every second, which then counts down a counting variable. But then I was told very often that this type of timer was not accurate and that I should try Date (). So my code looks like this:
@objc func startStopButton_Tapped() {
if startStopButton.titleLabel?.text == "Start" {
// Start timer
endTime = Date(timeInterval: TimeInterval(remainingSeconds), since: .now)
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: .common)
startStopButton.setTitle("Stopp", for: .normal)
} else {
// Stop timer
timer.invalidate()
startStopButton.setTitle("Start", for: .normal)
}
}
@objc func resetButton_Tapped() {
}
@objc func updateTime() {
if endTime > Date.now {
timerLabel.text = formatter.string(from: Date.now, to: endTime)
remainingSeconds = Int(endTime.timeIntervalSinceNow)
} else {
// Timer ended
timerLabel.text = formatter.string(from: TimeInterval(0))
timer.invalidate()
print("fertig")
}
}
But unfortunately it doesn't work well. For example, I want it to count down from 60 seconds, but when I start the timer it suddenly jumps to 58 instead of 59. So has someone already code that I can look at? Or who has suggestions for improvement? Warm greetings