简体   繁体   English

使用自定义解码器解码 Firestore 结构时获取 DocumentID

[英]Getting DocumentID when decoding Firestore struct with custom decodable

I have the following struct我有以下结构

struct Vehicle: Codable, Identifiable {
    @DocumentID var id: String?
    var name: String
}

As long as I use the default Swift decoder I can load Firestore entries without any issue (using document.data(as: ), and id contains the document ID.只要我使用默认的 Swift 解码器,我就可以毫无问题地加载 Firestore 条目(使用document.data(as: ),并且id包含文档 ID。

However I now need a custom decode function inside that struct, and that's where things go wrong.但是,我现在需要在该结构中自定义解码 function,这就是 go 错误的地方。

I can load all fields without any issue, but the document ID is not filled out.我可以毫无问题地加载所有字段,但未填写文档 ID。

I tried like this:我试过这样:

    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
        }

But it gives me nil .但它给了我nil

I found some other answers but they talk about DocumentReference which is a type that doesn't (or no longer?) exist.我找到了其他一些答案,但他们谈论的是DocumentReference ,这是一种不存在(或不再存在?)的类型。

How can I solve this?我该如何解决这个问题?

Thanks谢谢

To clarify, a DocumentReference is an object that holds the path to a firestore document and is the object you would call your platforms equivalent of .get() to retrieve data through a DocumentSnapshot .澄清一下, DocumentReference是一个 object ,它包含指向 firestore 文档的路径,并且是 object 您可以调用您的平台等效于.get()以通过DocumentSnapshot检索数据。 I am not terribly familiar with swift, but when decoding the object, you should be able to reference the ID as needed from the documentID property rather than the .data() method我对 swift 不是很熟悉,但是在解码 object 时,您应该能够根据需要从documentID属性而不是.data()方法引用 ID

Source: iOS Document Snapshot ID来源: iOS 文档快照 ID

Decode the Document ID using:使用以下方法解码文档 ID:

_id = try container.decode(DocumentID<String>.self, forKey: .id)

for the corresponding variable:对于相应的变量:

@DocumentID var id: String?

This will place the document ID into the ID variable (note the required "_" before id).这会将文档 ID 放入 ID 变量中(注意 id 之前需要的“_”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM