使用Swift Codable解码firestore文档时获取文档ID



我正在使用一个类来解码检索到的firestore文档,如果我不想操作数据,它会按预期工作:

class Room: Identifiable, Codable {
@DocumentID public var id:String?
var name:String
}

但是,如果我尝试使用自己的init来设置值,我就无法获得firestore文档ID?

class Room: Identifiable, Codable {
@DocumentID public var id:String?
var name:String


enum Keys:String, CodingKey {
case name
case capacity
case photo = "url"
}

required init(from decoder: Decoder) throws {
// How do I get the document ID to set the id value?
let container = try decoder.container(keyedBy: Keys.self)
name = try container.decode(String.self, forKey: .name)
capacity = try container.decode(Int.self, forKey: .capacity)
photo = try container.decode(String.self, forKey: .photo)
// Do some more stuff here...
}
}

在其他地方找到了答案,这非常有效。为带着相同查询到达这里的其他人发帖。

TL;DR-

使用以下方法对init函数中的DocumentReference进行解码:

ref = try container.decode(DocumentID<DocumentReference>.self, forKey: .ref)
.wrappedValue

更长的解释:我不会假装100%理解,但这里有一个很好的解释https://github.com/firebase/firebase-ios-sdk/issues/7242

最新更新