Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Firebase Datasnapshot to codable JSON data

I'm using Firebase Database and I'm attempting to retrieve and use data with NSObject. I'm receiving an NSUnknownKeyException error when running the app, causing it to crash.

NSObject:

class WatchList: NSObject {

    var filmid: Int?

}

Firebase Code:

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'm not sure of what could cause this.

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

like image 980
JSharpp Avatar asked Dec 07 '22 13:12

JSharpp


1 Answers

You can simply use JSONSerialization to convert the snapshot value property from Any to Data:

let data = try? JSONSerialization.data(withJSONObject: snapshot.value)

You can also extend Firebase DataSnapshot type and add a data and json string properties to it:

import Firebase 

extension DataSnapshot {
    var data: Data? {
        guard let value = value, !(value is NSNull) else { return nil }
        return try? JSONSerialization.data(withJSONObject: value)
    }
    var json: String? { data?.string }
}
extension Data {
    var string: String? { String(data: self, encoding: .utf8) }
}

usage:

guard let data = snapshot.data else { return }
like image 66
Leo Dabus Avatar answered Feb 15 '23 10:02

Leo Dabus