Bowenac
Bowenac

Reputation: 503

Save datepicker to userdefaults and set value on load

Trying to save datePicker date when changed as UserDefaults and set the datePicker date if this UserDefaults exists.

I have done research but everything I have found seems old and isn't working.

I seem to be having an issue setting the date from the saved UserDefaults. Pretty sure I'm doing this wrong. I'm just learning Xcode/Swift so I apologize if this should be obvious.

Saving date:

@IBOutlet weak var NotificationTime: UIDatePicker!
let notificationTimeKey = "notificationTime"

override func viewDidLoad(){
    super.viewDidLoad()

    //Not sure how to set the date
    if let dateValue = defaults.value(forKey: notificationTimeKey){
        NotificationTime.date = dateValue as! NSDate <--- Cannot assign value of type 'NSDate?' to type 'Date'
    }
}  

@IBAction func updateNotificationTime(_ sender: Any){
    let selectedDate = NotificationTime.date
    UserDefaults().set(selectedDate, forKey: notificationTimeKey)
}

Upvotes: 1

Views: 776

Answers (2)

David_2877
David_2877

Reputation: 327

I found another answer similar to the above code from Redit by 'chriswaco' https://www.reddit.com/r/Xcode/comments/faxfa8/how_do_you_save_a_date_form_a_date_picker/

Works in iOS 14 and Xcode 12.

SAVE: (put this within the DatePicker action func)

 let theDate = datePicker.date
 UserDefaults.standard.set( theDate, forKey:"myDateKey")

READBACK, i.e. (ViewDidLoad)

 if let savedDate = UserDefaults.standard.object(forKey:"myDateKey") as? Date{
    // do something with savedDate here
 }

Credit to chriswaco in Redit.

Upvotes: 0

rmaddy
rmaddy

Reputation: 318774

Your code for reading the date from UserDefaults and setting the date picker's date should be:

if let dateValue = defaults.object(forKey: notificationTimeKey) as? Date {
    NotificationTime.date = dateValue
}

Never use value(forKey:) unless you have a clear and understood reason to use key-value coding.

And don't use NSDate in Swift.

Also, variable and method names should start with lowercase letters. You should name your outlet notificationTime. Class and struct names start with uppercase letters.

Upvotes: 2

Related Questions