theDuncs
theDuncs

Reputation: 4843

Firebase Firestore - Using ServerTimeStamp in a Custom Object in Swift

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:

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!

Upvotes: 5

Views: 2297

Answers (2)

theDuncs
theDuncs

Reputation: 4843

OK I found the answer:

public struct City: Codable {
    let name: String
    @ServerTimestamp var createdAt: Timestamp?
}

Here, the createdAt is nil when I call setData. The server will populate this with the server value, and then the next time I fetch the data from the server it will be populated with the written datetime (and never overwritten)

Upvotes: 15

adri567
adri567

Reputation: 661

struct City: Codable {
    let createdAt: Double
    let nameCity: String
    init(name: String) {
       nameCity = name
       timestamp = FIRServerValue.timestamp()
        
    }
}

After this, you can call City(name: "Los Angeles"), and a timestamp will be created.

Upvotes: 0

Related Questions