I have a countdown timer in Xcode that stops working when my app goes out of focus - I have seen all apps with a timer never lose the count even when in the background - here is my code - I hope someone can advise me Thanks in advance Phil
// MARK: - Timer
extension ViewController {
func createTimer() {
if timer == nil {
let timer = Timer(timeInterval: 1.0,
target: self,
selector: #selector(updateTimer),
userInfo: nil,
repeats: true)
RunLoop.current.add(timer, forMode: .common)
timer.tolerance = 0.1
self.timer = timer
}
}
func cancelTimer() {
timer?.invalidate()
timer = nil
}
@objc func updateTimer() {
secondsg -= 1
print(secondsg) // I put this here to monitor the time (but it does not update
let hours = Int(secondsg) / 3600
let minutes = Int(secondsg) / 60 % 60
let seconds = Int(secondsg) % 60
lblTimeDisplay.textColor = UIColor.green
lblTimeDisplay.text = String(format:"%02i:%02i:%02i", hours, minutes, seconds)
if secondsg == 0 {
cancelTimer()
}
}
}