[英]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.