Search code examples
swiftuidatepickersaving-data

Save a selection from an UIDatePicker


So I have a UIDatePicker in Xcode. I need a way so that the UIdatePicker is saved automatically. So that the next time that user opens the app the UIDatePicker displays the same date that was inputed before he closed it last time. Here is some of my code

@IBOutlet weak var BirthdayPicker: UIDatePicker!
...
 override func viewDidLoad() {
    super.viewDidLoad()

    //__________________________________________________________________________
    // This makes sure the user doesnt use a date after the current date
    var components = DateComponents()
    components.year = -300

    let minDate = Calendar.current.date(byAdding: components, to: Date())

    components.year = 0
    components.day = 0
    components.hour = 0
    components.minute = 0
    components.second = 0
    let maxDate = Calendar.current.date(byAdding: components, to: Date())

    BirthdayPicker.minimumDate = minDate
    BirthdayPicker.maximumDate = maxDate
    //____________________________________

So whenever I open my app I get todays date. here's the screenshot This is the todays date

But what I really want when I open the app is

This is a random date that I just set it to

If you want me to be more specific or have any questions for me just leave a comment. I'm also not really sure of my code is useful but it’s something. Thank you.


Solution

  • UIDatePicker has property date which represents current Date selected in date picker. You goal should be saving this date somewhere. UserDefaults should be enough for this case.

    Start with creating IBAction for your date picker for event .valueChanged and when value is changed, save current date of your picker to UserDefaults.standard with key "BirthdayDate"

    @IBAction func datePickerChangedValue(_ sender: UIDatePicker) {
        UserDefaults.standard.set(sender.date, forKey: "BirthdayDate")
    }
    

    then in viewDidLoad if there is already saved date in for key BirthdayDate, set current date of BirthdayPicker

    if let date = UserDefaults.standard.object(forKey: "BirthdayDate") as? Date {
        BirthdayPicker.date = date
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        ...
        var components = DateComponents()
        components.year = -300
        let minDate = Calendar.current.date(byAdding: components, to: Date())
        BirthdayPicker.minimumDate = minDate
        BirthdayPicker.maximumDate = Date() // if `maxDate` is just current date, you can use `Date()`
    
        if let date = UserDefaults.standard.object(forKey: "BirthdayDate") as? Date {
            BirthdayPicker.date = date
        }
    }
    
    @IBAction func datePickerChangedValue(_ sender: UIDatePicker) {
        UserDefaults.standard.set(sender.date, forKey: "BirthdayDate")
    }