Search code examples
iosswiftnsuserdefaultsuidatepickeribaction

How can I use UserDefaults to store from UIDatePicker?


I am new to programming and to Swift. The app I'm building is vary simple and I want to add a simple local notification, triggered by a UIDatePicker that is set by the user. I've managed to set up the notification but I'm on my knees trying to understand how to keep the UIDatePicker from reseting each time I restart the app. Here's the relevant code (without the stuff going on in AppDelegate.swift):

 @IBAction func datePicker(_ sender: UIDatePicker) {

    let selectedDate = sender.date
    let delegate = UIApplication.shared.delegate as? AppDelegate
    delegate?.scheduleNotification(at: selectedDate)

}

Solution

  • Since Date does not conform to NSCoding, you cannot directly store it in user defaults. You need to convert it to a "property list type" (which means the type of things you can store in a property list, Int, Double, String, Dictionary etc). In this case, you will convert the Date to a Double:

    let selectedDate = sender.date
    let timeSince1970 = selectedDate.timeIntervalSince1970
    // now we have the double value, we can store it in user defaults! :)
    UserDefaults.standard.set(timeSince1970, forKey: "myDate")
    

    EDIT:

    Oops! It seems like I got this one wrong, you can actually directly store a Date in User Defaults:

    UserDefaults.standard.set(selectedDate, forKey: "myDate")
    

    To get back the stored date and set it as the selected date of the date picker, simply do this in viewDidLoad:

    let selectedDate = UserDefaults.standard.object(forKey: "myDate") as? Date
    myDatePickerOutlet.setDate(selectedDate ?? Date(), animated: false)
    

    If you stored a Double as the date, you can retrieve it like this:

    let selectedDate = Date(
        timeIntervalSince1970: UserDefaults.standard.double(forKey: "myDate"))