In a game screen, I use a background queue to count elapsed time in a game, this func is based on Daniel Galasko solution, a perfect solution for my app: it allows user to navigate through other VC, while timer is still on. The VC hierarchy is quite simple : the game settings VCs are handled in a tabBarController. The game screen is apart. User can change settings while timer is on. Settings are stored in CoreData.
In my game screen, where I need to display the timer, I have a label that displays the elapsed time and 2 buttons : Play/Pause button and Reset button.
I call my setup timer func in ViewDidLoad. The default value for my timer is the stored value in CoreData, it has been defined in settings. And this value is incremented by 1 every second when timer is on. I also have a static let shared that keep timer status (resumed / suspended).
When I'm on the game screen, and if my timer is suspended, my play/Pause button works perfect : I can navigate to others views (mean dismiss my screen game), present again my screen game and resume my counter. It updates my label correctly.
The problem is when I dismiss the game screen view while timer is running. Timer works (print func shows that timer is still running), but when I present the screen again, I'm unable to pause/resume/restart it, and my label is stopped at the second I came back... while timer is still running back.
private var counter: Int16?
var t = RepeatingTimer(timeInterval: 1)
let gameIsOn = isGameOnManager.shared
override func viewDidLoad() {
super.viewDidLoad()
print("is timer On ? \(String(describing: gameIsOn.isgameOn))")
buildTimer()
if gameIsOn.isgameOn == true {
resumeTapped = true
t.resume()
PlayB.setImage(UIImage(named:"pause"), for: .normal)
} else {
resumeTapped = false
}
}
func buildTimer(){
self.t.eventHandler = {
self.counter! += 1
print("counter \(String(describing: self.counter!))")
self.coreDataEntity?.TimeAttribute = self.counter ?? 0
self.save()
DispatchQueue.main.async {
self.dataField.text = String(describing: self.counter ?? 0)
}
}
}
@objc func didTapButton(_ button: UIButton) {
if resumeTapped == false {
t.resume()
resumeTapped = true
gameIsOn.isgameOn = true
PlayB.setImage(UIImage(named:"pause"), for: .normal)
}
else if resumeTapped == true {
t.suspend()
resumeTapped = false
gameIsOn.isgameOn = false
PlayB.setImage(UIImage(named:"play"), for: .normal)
}
}