Swift 4的JSONDecoder可以与Firebase Realtime Database一起使用吗? [英] Can Swift 4's JSONDecoder be used with Firebase Realtime Database?
问题描述
我正在尝试从Firebase DataSnapshot解码数据,以便可以使用JSONDecoder对其进行解码.
I am trying to decode data from a Firebase DataSnapshot so that it can be decoded using JSONDecoder.
当我使用URL通过网络请求(获取Data对象)访问数据时,我可以很好地解码该数据.
I can decode this data fine when I use a URL to access it with a network request (obtaining a Data object).
However, I want to use the Firebase API to directly obtain the data, using observeSingleEvent as described on this page.
但是,当我这样做时,似乎无法将结果转换为Data对象,而我需要使用JSONDecoder.
But, when I do this, I cannot seem to convert the result into a Data object, which I need to use JSONDecoder.
是否可以使用DataSnapshot进行JSON解码的新样式?这怎么可能?我似乎无法弄清楚.
Is it possible to do the new style of JSON decoding with a DataSnapshot? How is it possible? I can't seem to figure it out.
推荐答案
我创建了一个名为 CodableFirebase 提供专门为Firebase设计的Encoders
和Decoders
.
I have created a library called CodableFirebase that provides Encoders
and Decoders
that are designed specifically for Firebase.
因此,对于上面的示例:
So for the example above:
import Firebase
import CodableFirebase
let item: GroceryItem = // here you will create an instance of GroceryItem
let data = try! FirebaseEncoder().encode(item)
Database.database().reference().child("pathToGraceryItem").setValue(data)
以下是读取相同数据的方式:
And here's how you will read the same data:
Database.database().reference().child("pathToGraceryItem").observeSingleEvent(of: .value, with: { (snapshot) in
guard let value = snapshot.value else { return }
do {
let item = try FirebaseDecoder().decode(GroceryItem.self, from: value)
print(item)
} catch let error {
print(error)
}
})
这篇关于Swift 4的JSONDecoder可以与Firebase Realtime Database一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!