Search code examples
swiftfirebasegoogle-cloud-firestoretimestampnsuserdefaults

Storing Firestore Timestamp in User Defaults


I am a new Swift developer. I am using Xcode 10.2 and Swift 4.2.

I am trying to store a Firestore Timestamp in the user defaults and retrieve it. The problem I'm having is the first time I retrieve the timestamp, it may be nil so I would like to have a default value. But I don't know how to format any date as a Firestore Timestamp so I can indicate a default of January 1, 2000. I reviewed the firebase documentation but could not find how to take a readable date and format it as a timestamp (it seems all the the methods are deprecated by firebase).

Here is my code to read the stored date with an attempt to use January 1, 2000 as a default, but this does not work:

// Get a reference to a default date of January 1, 2000.
    let dateformatter = DateFormatter()
    let defaultDate = dateformatter.date(from: "01/01/2000 12:00 AM")

// Get the last date the table was updated.
    let lastDateNSData = UserDefaults.standard.object(forKey: Constants.LocalStorage.rateTableTimeStamp) as? Data
    let lastDate = NSKeyedUnarchiver.unarchiveObject(with: lastDateNSData ?? Data(Timestamp(date: defaultDate!))) as! Timestamp

I am getting an error on the Data(Timestamp(date: defaultDate!)) that says 'Timestamp' does not conform to expected type 'Sequence' I think it is because of how I formatted defaultDate using dateformatter. But I don't know another way to do it.

In case it helps, here is my code to write the current date as a timestamp to defaults:

// Update the timestamp.
    let now = Timestamp(date: Date())
    let nsNow = NSKeyedArchiver.archivedData(withRootObject: now)
    UserDefaults.standard.set(nsNow, forKey: Constants.LocalStorage.rateTableTimeStamp)

Solution

  • You need to set it as object

    UserDefaults.standard.set(Date(), forKey:"key")
    

    And read

    if let date = UserDefaults.standard.object(forKey: "key") as? Date {
       //// 
    }
    

    if UserDefaults.standard.bool(forKey: "Opened") { 
        // set date here
        UserDefaults.standard.set(true, forKey: "Opened")
    }