How to store date in userdefaults?

故事扮演 提交于 2020-06-23 07:04:17

问题


I'd like to record the history of her entry into the textfield. I intend to register this with UserDefaults. But when I try to save it with UserDefaults, "cannot assign value of type 'nsdate'?'to type 'String' " Error. I don't think it's accepting textfield data because it's string. And how can I keep history in memory?

formatteddate and formatteddate2 give this error. The date output is as follows : 20/04/2019 20:23

let token = try? keychain.getString("chipnumbernew")
        chip1InfoString = token

        var time = NSDate()
        var formatter = DateFormatter()
        formatter.dateFormat = "dd/MM/yyyy HH:mm"
        var formatteddate = formatter.string(from: time as Date)
        var formatteddate2 = formatter.string(from: time as Date)

        timertextNew.text = formatteddate
        timertext2New.text = formatteddate2


        let RetrivedDate = UserDefaults.standard.object(forKey: "timertext") as? NSDate

       formatteddate = RetrivedDate

        let RetrivedDate2 = UserDefaults.standard.object(forKey: "timertext2") as? NSDate
        formatteddate2 = RetrivedDate2

回答1:


If you only want to display the date value you can convert and store it as string otherwise you convert/format it after you have read it, either way you should make sure you use the same type when saving and reading

//save as Date
UserDefaults.standard.set(Date(), forKey: key)

//read
let date = UserDefaults.standard.object(forKey: key) as! Date
let df = DateFormatter()
df.dateFormat = "dd/MM/yyyy HH:mm"
print(df.string(from: date))

// save as String
let df = DateFormatter()
df.dateFormat = "dd/MM/yyyy HH:mm"
let str = df.string(from: Date())
UserDefaults.standard.setValue(str, forKey: key)

// read
if let strOut = UserDefaults.standard.string(forKey: key) {
    print(strOut)
}



回答2:


Your problem is that you are retrieving NSDate from the user default storage and then trying to assign them to a String (formatteddate).

Try this;

  formatteddate = formatter.string(from: RetrivedDate as Date)



回答3:


You can set date and store persistence with user defaults:

UserDefaults.standard.set(Date(),forKey:”keyname”) as? Date

Remember to use conditional cast operator ? to avoid crash.

To save date as string you can do it by following below post: Convert NSDate to String in iOS Swift



来源:https://stackoverflow.com/questions/55776143/how-to-store-date-in-userdefaults

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