Home / IOS Development / ios – Firebase Firestore Swift, timestamp but server time?

ios – Firebase Firestore Swift, timestamp but server time?



The syntax you are looking for is:

"created": FieldValue.serverTimestamp()

This creates a token that has no date value per se. The value is assigned by the server when this writing is actually written. Time stamps for writing are decent.

Reading them is just a little less straightforward. When reading documents that contain them, you will configure how they are handled.

doc.get("created", serverTimestampBehavior: .none)
doc.get("created", serverTimestampBehavior: .previous)
doc.get("created", serverTimestampBehavior: .estimate)

none will actually give you one nil value if the value has not yet been set by the server. For example, if you are writing a document that relies on latency-compensated returns, you will get it nil (on the waiting time compensated return). When the server finally performs the writing and sets the value, it will stop being nil.

previous will give you any previous values, if they exist.

estimate will give you a value, but it will be an estimate of what the value is likely to be. For example, if you are writing a document that relies on latency-compensated returns, estimate will give you a date value on the latency-compensated return, even if the server has not yet set the value.

It is for these reasons that handling Firestore̵

7;s timestamps can lead to more returns from your instant listeners (returns for updating tokens). A quick alternative to the token world is to use a Unix timestamp that has none of these complexities:

extension Date {
    var unixTimestamp: Int {
        return Int(self.timeIntervalSince1970 * 1_000) // millisecond precision
    }
}

"created": Date().unixTimestamp

This is definitely the best explanation of how timestamps work (written by the same Doug Stevenson who actually posted an answer): https://medium.com/firebase-developers/the-secrets-of-firestore-fieldvalue-servertimestamp-revealed – 29dd7a38a82b


Source link