Save datePicker value using NSUserdefaults(xcode,swift2)

限于喜欢 提交于 2020-01-04 01:25:39

问题


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)
  }

回答1:


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)
}



回答2:


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.




回答3:


You can read about using UserDefault here Except "setInteger" and "integerForKey" you can use setValue and valueForKey with adding as! String, for example

It would be like

someVariable = save.valueForKey(forKey: "title") as! String


来源:https://stackoverflow.com/questions/31936095/save-datepicker-value-using-nsuserdefaultsxcode-swift2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!