Hightower98 Hightower98 - 3 years ago 177
Swift Question

Setting UILabel from UserDefualts

I have saved a date using UserDefaults and my values are being saved and I trying to present my saved date as a string in my view controller but it comes up blank. Am I implementing it wrong?

@IBOutlet weak var timeLabel: UILabel!

let formatter = DateFormatter()

func savedate(){

UserDefaults.standard.set(datePicker.date, forKey: keyDate)

}

func loadDate(animation: Bool) {

guard let loadedDate = UserDefaults.standard.object(forKey: keyDate) as? Date else { return }

datePicker.setDate(loadedDate, animated: true)

print(loadedDate)

let loadedValue = formatter.string(from: loadedDate)
timeLabel.text = loadedValue
}

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
loadDate(animation: true)
}
@IBAction func saveTimeValue(_ sender: Any) {
saveDate()
}

Answer Source

Your problem is that you didn't set your date formatter options. As it is it will return an empty string for any date:

Try

let formatter = DateFormatter()
formatter.string(from: Date())  // ""

To format your date properly using a localized description you can take a look at this answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download