stakabekor
stakabekor

Reputation: 533

How to store date in userdefaults?

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

Upvotes: 38

Views: 35365

Answers (4)

Ihwan
Ihwan

Reputation: 49

you can always create an extension for saving and retrieving the date in userdefault. here the example code:

import Foundation

extension UserDefaults {
    func set(date: Date?, forKey key: String){
        self.set(date, forKey: key)
    }
    
    func date(forKey key: String) -> Date? {
        return self.value(forKey: key) as? Date
    }
}

let userDefault = UserDefaults.standard
userDefault.set(date: Date(), forKey: "timertext")
print(userDefault.date(forKey: "timertext") ?? "")

Upvotes: 4

jameshfisher
jameshfisher

Reputation: 36599

The following saves a Date object as a Double (a.k.a. TimeInterval). This avoids any date formatting. Formatting can lose precision, and is unnecessary since the string is not intended for users to read.

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

// read
let date = Date(timeIntervalSince1970: UserDefaults.standard.double(forKey: key))

Upvotes: 73

Joakim Danielson
Joakim Danielson

Reputation: 52088

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

Upvotes: 84

john elemans
john elemans

Reputation: 2676

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)

Upvotes: 0

Related Questions