Datasnapshot转换为可编码的JSON数据

Datasnapshot转换为可编码的JSON数据

本文介绍了将Firebase Datasnapshot转换为可编码的JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Firebase数据库,并尝试使用NSObject检索和使用数据.运行应用程序导致崩溃时,我收到NSUnknownKeyException错误.

I am using Firebase Database and am attempting to retrieve and use data using NSObject. I am receiving a NSUnknownKeyException error when running the app causing it to crash.

NSObject:

class WatchList: NSObject {

var filmid: Int?

}

Firebase代码:

Firebase Code:

ref.child(用户").child(uid!).child(监视列表").observe(DataEventType.childAdded,其中:{(info)in

ref.child("users").child(uid!).child("watchlist").observe(DataEventType.childAdded, with: { (info) in

            print(info)

            if let dict = info.value as? [String: AnyObject] {
                let list = WatchList()
                list.setValuesForKeys(dict)
                print(list)
            }

    }, withCancel: nil)

我不确定是什么原因造成的.

I am not sure of what could cause this.

还可以增强此解决方案的一种方法是获取这些数据,并且可以不使用NSObject而是将Codable和JSONDecoder与Firebase数据一起使用?

Also to enhance this solution is their a way to take this data and instead of using NSObject I could use Codable and JSONDecoder with the Firebase data?

推荐答案

现在是2021年.

Firebase最终添加了对Firestore文档解码的支持.只需让您的对象符合 Codable 并像这样进行解码即可:

It's 2021 now.

Firebase finally added support for decoding Firestore documents. Just let your objects conform to Codable and decode like this:

let result = Result {
  try document?.data(as: City.self)
}
switch result {
case .success(let city):
    if let city = city {
        print("City: \(city)")
    } else {
        print("Document does not exist")
    }
case .failure(let error):
    // A `City` value could not be initialized from the DocumentSnapshot.
    print("Error decoding city: \(error)")
}

请不要忘记添加'FirebaseFirestoreSwift'窗格,然后将其导入到您的文件中.

Just don't forget to add the 'FirebaseFirestoreSwift' pod and then import it into your file.

了解更多: https://firebase.google.com/docs/firestore/query-data/get-data#custom_objects

原始答案

在这里使用的一个非常不错的库是 Codable Firebase ,我也在我的项目中使用了它.只需使您的类/结构符合 Codable 协议,然后使用FirebaseDecoder将Firebase数据解码为Swift对象即可.

A really nice library to use here is Codable Firebase which I am also using in my project. Just make your class / struct conform to Codable protocol and use FirebaseDecoder to decode your Firebase data into a Swift object.

示例:

Database.database().reference().child("model").observeSingleEvent(of: .value, with: { snapshot in
    guard let value = snapshot.value else { return }
    do {
        let model = try FirebaseDecoder().decode(Model.self, from: value)
        print(model)
    } catch let error {
        print(error)
    }
})

这篇关于将Firebase Datasnapshot转换为可编码的JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:46