let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm "
let selectedDate = dateFormatter.string(from: sender.date)
UserDefaults.standard.set(selectedDate, forKey: "date")
print(selectedDate)
\\method to reload the selected time inside the viewdidLoad func
let selectedDate = UserDefaults.standard.object(forKey: "date")
example.setDate(selectedDate as! Date ?? Date(), animated: false)
But when I run the application it returns this error
Could not cast value of type '__NSCFString' (0x108e8b4f0) to 'NSDate' (0x108e8c0d0).
I converted to HH: mm because I want to record only the time in this format, but I do not know how I'm going to handle it
You should be storing the Date object itself in
UserDefaultsand not its String representation. In most use cases, it makes more sense to store aDateobject, sinceDateobjects represent an absolute point in time and hence you can use them for date comparison or to convert them to local times.Moreover, it looks like that the
setDatefunction actually expects aDateobject and not a String, hence it doesn't make sense to generate a String representation of a Date and then store that inUserDefaults.