繁体   English   中英

使用Decodable通过Firestore获取对象和文档ID

[英]Using Decodable to get the object and document ID with Firestore

我有一个简单的User类,它包含以下字段:

{ 
  "localIdentifier": "xyc9870",
  "isOnline": false,
  "username": "ZS"
}

我想使用Swift的Decodable轻松地将QueryDocumentSnapshot转换为类型安全的Swift结构。 我还想确保从QueryDocumentSnapshot获取documentID以便稍后更新对象。

这是我目前正在使用的解码,但显然它错过了documentId

struct User: Decodable {

    let localIdentifier: String
    let username: String
    let isOnline: Bool

}

会喜欢这里的一只手。 谢谢!

我自己写了一个简单的便利扩展,只是将documentID带入data JSON,然后我可以使用下面的简单struct

extension QueryDocumentSnapshot {

    func prepareForDecoding() -> [String: Any] {
        var data = self.data()
        data["documentId"] = self.documentID

        return data
    }

}

解码使用:

struct User: Decodable {

    let documentId: String
    let localIdentifier: String
    let username: String
    let isOnline: Bool

}

if let user = try? JSONDecoder().decode(User.self, fromJSONObject: doc.prepareForDecoding()) {
    ...
}

编辑:

我的JSONDecoder扩展

extension JSONDecoder {
    func decode<T>(_ type: T.Type, fromJSONObject object: Any) throws -> T where T: Decodable {
        return try decode(T.self, from: try JSONSerialization.data(withJSONObject: object, options: []))
    }
}

暂无
暂无

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

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