Firebase Firestore Swift,时间戳但服务器时间?

时间:2020-07-03 18:16:17

标签: ios swift firebase google-cloud-firestore

在Firestore中,我像这样添加时间戳字段

    var ref: DocumentReference? = nil
    ref = Firestore.firestore()
        .collection("something")
        .addDocument(data: [
            "name": name,
            "words": words,
            "created": Timestamp(date: Date())
        ]) { ...
            let theNewId = ref!.documentID
            ...
    }

那很好,效果很好,但实际上并不正确。应该使用Firestore提供的“服务器时间戳”。

请注意,这是在iOS(Swift)和Firestore上,而不是在Firebase上。

获取服务器时间戳的语法是什么?

3 个答案:

答案 0 :(得分:2)

您要查找的语法是:

"created": FieldValue.serverTimestamp()

这将创建一个本身没有日期值的令牌。实际写入此写入时,该值由服务器分配。编写时间戳很简单。

阅读它们并不那么简单。阅读包含它们的文档时,您将需要配置它们的处理方式。

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

none实际上会为您提供一个nil值,如果服务器尚未设置该值。例如,如果您编写的文档依赖于延迟补偿的收益,您将获得nil(基于延迟补偿的收益)。当服务器最终执行写入并设置值时,它将不再是nil

previous将为您提供任何以前的值(如果存在)。

estimate会给您带来价值,但这只是对价值可能的估算。例如,如果您要编写依赖于经延迟补偿的收益的文档,那么即使服务器尚未设置其价值,estimate也会为您提供基于经延迟补偿的收益的日期值。

基于这些原因,处理Firestore的时间戳可能会导致快照侦听器产生更多返回(更新令牌的返回)。替代令牌世界的一种Swift替代方法是使用没有以下任何复杂性的Unix时间戳:

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

"created": Date().unixTimestamp

这绝对是时间戳如何工作的最好解释(由同一位道格·史蒂文森(Doug Stevenson)撰写,他实际上发布了答案):https://medium.com/firebase-developers/the-secrets-of-firestore-fieldvalue-servertimestamp-revealed-29dd7a38a82b

答案 1 :(得分:1)

如果要使用服务器时间戳作为字段的值,请使用FieldValue.serverTimestamp()。这将返回令牌值,写入完成后将在服务器上解释该令牌值。

答案 2 :(得分:-2)

使用Timestamp(date: Date())时,您将使用给定的日期初始化时间戳。为您提供服务器时间戳记的简单解决方案是像这样Timestamp()那样将构造函数参数保留为空。在官方documentation

中了解更多信息