Countdown Timer in background

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 :slight_smile: 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()
   }

  }
    
}

I am not an xcode developer but I am a React Native developer.

Perhaps someone has a better option, but I can think of two things offhand.

The first would be to compute the elapsed time from the system time instead of creating your own timer.

The other option would be to run your own timer but also store the timestamp of when the timer was started. When the app is foregrounded, recalculate the elapsed time and restart your timer based on that.

Just to +1 what @kevinSmith says, that’s how most timer apps work. The system will kill iOS apps in the background after a short period of time for both security and battery reasons. So storing the last time and calculating against that is far far easier than some faffy workaround (as an aside, for a huge recent real-life example of problems of building apps that work when minimised vs. iOS killing background processes, see the issues government-tendered developers have had building track and trace apps).

1 Like