This is a timer App and I would like for the timer to pause when the app gets killed and when you reopen the app I would like the timer to display the last known time.
I have setup a struct for the data to be saved to.
let defaults = UserDefaults.standard
private enum TimeData {
static let allCurrentTime = "allCurrentTime"
}
override func viewDidLoad() {
super.viewDidLoad()
checkForSavedTimer()
marksSavedData()
theTimer.text = "00:00:00"
theTimer.font = UIFont(name: "Menlo-BoldItalic", size: 40)
marksTableView.isHidden = false
}
//I set the timer info to the struct (see below)
@objc func updateTimerLabel() {
seconds += 1
if seconds == 60 {
minutes += 1
seconds = 0
}else if minutes == 60 {
hours += 1
minutes = 0
}
timerString = "\(hours):\(minutes):\(seconds)"
theTimer.text = timerString
defaults.set(theTimer.text, forKey: TimeData.allCurrentTime)
}
// I then created a function which I called in the viewdidload above
func checkForSavedTimer() {
let allCurrentTime = defaults.value(forKey: TimeData.allCurrentTime) as? String ?? ""
theTimer.text = allCurrentTime
}
I thought this would take the string from theTimer save it to the UserDefaults and then in viewDidLoad bring it back out and save it to "theTimer.text" BUT the result is 00:00:00
When you are calling your
checkForSavedTimer()function, it is probably getting the correct value fromUserDefaultsbut then you are setting the timer text back to00:00:00two lines later. You will need to remove that line and add some logic within yourcheckForSavedTimer()function to set the value to00:00:00if the value fromUserDefaultsisnilAlso it is better to use
.string(forKey:)to get aStringfromUserDefaultsbecause then the value is already typed for you and therefore you don't need to addas? String