Can Swift 4's JSONDecoder be used with Firebase Realtime Database?

后端 未结 7 1636
有刺的猬
有刺的猬 2020-12-28 19:39

I am trying to decode data from a Firebase DataSnapshot so that it can be decoded using JSONDecoder.

I can decode this data fine when I use a URL to access it with a

相关标签:
7条回答
  • 2020-12-28 20:35

    You can convert the value returned by Firebase to Data, and then decode that.

    Add this extension to your project:

    extension Collection {
        //Designed for use with Dictionary and Array types
        var jsonData: Data? {
            return try? JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
        }
    }
    

    Then use it to convert the value of the observed snapshot into data, which can then be decoded:

    yourRef.observe(.value) { (snapshot) in
        guard snapshot.exists(),
           let value = snapshot.value as? [String],
           let data = value.jsonData else { 
           return
        }
        //cast to expected type
        do {
            let yourNewObject =  try JSONDecoder().decode([YourClass].self, from: data)
        } catch let decodeError {
            print("decodable error")
        }
    }
    
    0 讨论(0)
提交回复
热议问题