【问题标题】:How to Codable firebase timestamp in ios swift5?如何在 ios swift5 中编码 firebase 时间戳?
【发布时间】:2020-01-20 13:49:23
【问题描述】:

我正在尝试使用 FirebaseDecoder() 解码 firebase 集合。这是我使用的模型

方法一

struct firebaseApplication:Codable {

var uid:String?
var status:String?
var jobId:String?
var companyId:String?
var createdDate: Timestamp? // or  //    Date? // or // String?

}

如果我评论 createdDate 则结果正在获取。否则没有结果。我尝试将 createdDate 设为 Timestamp?Date?string?,所有情况都没有结果。

我尝试了另一种工作正常的方法,就是这样

方法二

struct ApplicationCollection:CustomStringConvertible {
var description: String
var uid: String
var status:String
var jobId:String
var companyId:String
var createdDate:Date

init(Dict:[String:Any]) {

    self.uid = Dict["uid"] as? String ?? ""
    self.status = Dict["status"] as? String ?? ""
    self.jobId = Dict["jobId"] as? String ?? ""
    self.companyId = Dict["companyId"] as? String ?? ""
    let str = Dict["createdDate"] as? Timestamp ?? Timestamp()
    self.createdDate = str.dateValue()
    self.description = "[uid: \(uid),status: \(status),jobId: \(jobId),companyId: \(companyId),createdDate: \(createdDate)]"

}

init?(data: Data) {
    guard let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return nil }
    self.init(Dict: json)
}
init?(json: String) {
    self.init(data: Data(json.utf8))
}
}

方法 2 可以很好地获取所有数据以及 createDate

为什么在 Method 1 的情况下没有得到 createDate ?我错过了什么吗?

如何解决

【问题讨论】:

  • 如何编码是什么意思?

标签: ios swift google-cloud-firestore swift5


【解决方案1】:

看起来方法 2 有效,因为您手动将变量映射到键/值对。

方法 1 可能不起作用,因为您试图将字符串映射到自定义类型(不确定 TimeStamp 是否可编码,因为未提供实现)而不是原始字符串。也许在方法一中将创建的日期设置为字符串,并为该字符串的日期对象创建一个 accessor()。

方法 2 似乎您知道它是一个字符串,但将 createdDate 设置为该时间戳的dateValue,因为类型正在对齐。

您能否发布您的 Timestamp 实施以供审核?

【讨论】:

  • 我尝试了该部分也将 createdDate 设置为 String 仍然没有响应。即使我没有得到任何结果,它也正在赶上阻止。时间戳的实现有什么用。模型不接受解码器。
  • 在 Method2 中,我也给出了确切的数据类型,即 as?时间戳??时间戳()
  • @chandra1234 Apple 支持这个库吗? github.com/alickbass/CodableFirebase
【解决方案2】:

我一直在使用https://github.com/alickbass/CodableFirebase 项目来为我节省大量关于这类东西的代码。它确实有助于处理 FireStore,它还处理时间戳。

【讨论】:

  • 我也在使用同一个。我上面提到的“FirebaseDecoder()”你可以看到
  • @drekka 可以用时间戳举任何例子。我也在尝试同样的
【解决方案3】:

我找到了问题的解决方案。

我弄错了,在解码Timestamp() 时,我们必须使用FirestoreDecoder() 而不是FirebaseDecoder

这是我从 firebase 更改为 firestore

let decoder = FirebaseDecoder()
                let data = try decoder.decode(firebaseApplicationCollection.self, from: i.data())

而不是

let decoder = FirestoreDecoder()
                let item = try decoder.decode(firebaseApplicationCollection.self, from: i.data())

我希望这个答案能帮助其他人在 firebase 中解码 Timestamp 时找出确切的问题

【讨论】:

    猜你喜欢
    • 2022-06-28
    • 2021-11-23
    • 2017-05-16
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多