I am using Firebase Cloud Firestore in my project and have created Custom Objects to handle the incoming and outgoing data. This works perfectly for my needs - with one exception.
I would like to set a serverTimestamp onto my objects. I have read the docs and see that I can do this like this. The docs state that I can use FieldValue.serverTimestamp() in the setData and updateData calls, and shows the following example:
db.collection("objects").document("some-id").updateData([
"lastUpdated": FieldValue.serverTimestamp(),
]) { err in
...
}
However, in my code, I pass the custom object into these functions, like this:
let city = City(name: "Los Angeles")
do {
try db.collection("cities").document("LA").setData(from: city)
} catch let error {
print("Error writing city to Firestore: \(error)")
}
So, what I want is to add a new property to my custom class, which will do two things:
- When creating the data for the first time will set a serverTimestamp
- When fetching the data will store the timestamp as a date I can use.
What do I need to do to my custom class to make this happen?
public struct City: Codable {
let name: String
let createdAt: Date
}
THANK YOU in advance for your help!