Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save datePicker value using NSUserdefaults(xcode,swift2)

How can we save the value of datepicker through nsuserdeafaults or anything.For example if a person chooses 5 pm then when he return to app he should see 5pm on the datepicker.I do not know how to include nsusersdefault into this below is the code

@IBAction func NotificationButtonTapped(sender: AnyObject)
{
    cancelLocalNotificationsWithUUID("NotificationID")

    //dateformatter for alert
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "hh:mm a"
    var strDate = dateFormatter.stringFromDate(datePicker.date)

    var notifications:UILocalNotification = UILocalNotification()
    notifications.fireDate = datePicker.date
    notifications.timeZone = NSTimeZone.defaultTimeZone()
    notifications.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
    notifications.soundName = UILocalNotificationDefaultSoundName
    notifications.repeatInterval = NSCalendarUnit.CalendarUnitDay
    notifications.userInfo = ["UUID": "NotificationID"]
    notifications.alertBody = "Quote of the day"
    UIApplication.sharedApplication().scheduleLocalNotification(notifications)
  }
like image 890
Motivation gym5 Avatar asked Feb 25 '26 09:02

Motivation gym5


2 Answers

You can do the following:

var datePicker = /* Get Your Date Picker from somewhere */

// Store value using User Defaults
let currentDate = datePicker.date
NSUserDefaults.standardUserDefaults().setObject(currentDate, forKey: "Current-Date")

// Retrieve Value using User Defaults
if let date = NSUserDefaults.standardUserDefaults().objectForKey("Current-Date") as? NSDate {
    datePicker.setDate(date, animated: true)
}
like image 62
David Silverfarmer Avatar answered Feb 26 '26 22:02

David Silverfarmer


You can convert date object to string.

Then store it in user defaults.

And again to use it, you can again convert it from string to date.

Hope this helps.

like image 40
Bharat Nakum Avatar answered Feb 26 '26 22:02

Bharat Nakum