簡體   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