问题
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 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 am 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 I could use Codable and JSONDecoder with the Firebase data?
回答1:
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.
Example:
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)
}
})
回答2:
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 }
来源:https://stackoverflow.com/questions/53565519/converting-firebase-datasnapshot-to-codable-json-data