[英]Getting DocumentID when decoding Firestore struct with custom decodable
我有以下结构
struct Vehicle: Codable, Identifiable {
@DocumentID var id: String?
var name: String
}
只要我使用默认的 Swift 解码器,我就可以毫无问题地加载 Firestore 条目(使用document.data(as:
),并且id
包含文档 ID。
但是,我现在需要在该结构中自定义解码 function,这就是 go 错误的地方。
我可以毫无问题地加载所有字段,但未填写文档 ID。
我试过这样:
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let id = try container.decodeIfPresent(DocumentID<String>.self, forKey: .id) {
self.id = id.wrappedValue
}
但它给了我nil
。
我找到了其他一些答案,但他们谈论的是DocumentReference
,这是一种不存在(或不再存在?)的类型。
我该如何解决这个问题?
谢谢
澄清一下, DocumentReference
是一个 object ,它包含指向 firestore 文档的路径,并且是 object 您可以调用您的平台等效于.get()
以通过DocumentSnapshot
检索数据。 我对 swift 不是很熟悉,但是在解码 object 时,您应该能够根据需要从documentID
属性而不是.data()
方法引用 ID
来源: iOS 文档快照 ID
使用以下方法解码文档 ID:
_id = try container.decode(DocumentID<String>.self, forKey: .id)
对于相应的变量:
@DocumentID var id: String?
这会将文档 ID 放入 ID 变量中(注意 id 之前需要的“_”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.