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 from UserDefaults
but then you are setting the timer text back to 00:00:00
two lines later. You will need to remove that line and add some logic within your checkForSavedTimer()
function to set the value to 00:00:00
if the value from UserDefaults
is nil
override func viewDidLoad() {
super.viewDidLoad()
checkForSavedTimer()
marksSavedData()
// Remove this -> theTimer.text = "00:00:00"
theTimer.font = UIFont(name: "Menlo-BoldItalic", size: 40)
marksTableView.isHidden = false
}
func checkForSavedTimer() {
// Set the timer text to the value from UserDefaults or "00:00:00" if the value is nil
theTimer.text = defaults.string(forKey: TimeData.allCurrentTime) ?? "00:00:00"
}
Also it is better to use .string(forKey:)
to get a String
from UserDefaults
because then the value is already typed for you and therefore you don't need to add as? String