【问题标题】:Send timestamp to firebase using firebase funtions使用 firebase 函数向 firebase 发送时间戳
【发布时间】:2021-11-24 05:09:32
【问题描述】:

我需要使用 Firebase 函数将具有 Firebase Timestamp 对象的日期保存到 Cloud Firestore。

有问题的代码:

import FirebaseFunctions

lazy var functions = Functions.functions(region: "europe-west3")

let stamp = Timestamp(date: Date()) —> Not working

self.functions.httpsCallable("userUpdate").call(["id": user.uid, “startDate”: stamp]) { (result, error) in
                if let error = error {
                        print("##### update error \(error)”)
                    }
                }
                
                if let res = result {
                    if let fireData = (res.data as? [String: Any]) {
                        debugPrint("#####  Success update Data -> \(fireData["data"])")
                    }
                }
            }

问题是 Firebase 无法识别 Timestamp 格式并引发错误:

'不支持的类型:值 的 FIRTimestamp'

如果我尝试使用以下格式发送日期,但服务器上的日期格式错误,它显示有一个字符串并且没有时间戳。

let date = DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .none)

任何让 Firebase 识别我发送的日期的解决方案都有时间戳?

【问题讨论】:

    标签: ios swift firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    Callable Cloud Functions 只知道如何发送/接收 JSON 类型,而Timestamp 不是 JSON 类型。

    解决此问题的最简单方法是将 seconds and nanoseconds 作为单独的数字(它们是有效的 JSON 类型)发送,然后从 Cloud Functions 代码中的这些数字重构 Timestamp object

    【讨论】:

    • 对不起,我不明白,你是如何构建对象的?
    • 您可以将秒和纳秒传递给服务器上的Timestamp 构造函数。我链接了 JavaScript 文档,但 Node.js 中应该存在相同的构造函数。
    • “传递服务器上的对象”我很困惑,因为我试图用 iOS swift 完成任务,我不知道用 JavaScript 或 Node.js 做什么
    • 谁编写了userUpdate 函数?他们期望startDate 参数有什么价值?
    • 如前所述:您只能将 JSON 类型传递给可调用函数,而 Firestore 的 Timestamp 不是原生 JSON 类型。如果后端人员只是说“时间戳”而没有指定,他们可能只是表示以毫秒为单位的时间戳,这在 Firestore/iOS 之外更为常见。这只是一个数值(自纪元开始以来的毫秒数),您可以在 Swift 中使用NSDate().timeIntervalSince1970 * 1000 获得它。
    猜你喜欢
    • 2018-09-27
    • 2019-02-26
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多