I have an app in Android and I'm building the iOS version of it, but when I try to fetch user data into my model class I get an error, i know its because some nodes dont have all keys inside it, but this is ok on Android, i dont know how to deal with it on Swift 3. You can see my data on the link in the end of this post.
I get this doing a .childadded:
Fatal error: unexpectedly found nil while unwrapping an Optional value
This is my model class:
struct User {
var name: String
var age: String
var gender: String
var description: String
var hair:String
var skin:String
var tel:String
init(name: String, age: String, gender: String, hair: String, skin: String, tel: String, description: String) {
self.name = name
self.age = age
self.gender = gender
self.description = description
self.hair = hair
self.skin = skin
self.tel = tel
}
init(snapShot: FIRDataSnapshot){
self.name = (snapShot.value! as! NSDictionary)["name"] as! String
self.age = (snapShot.value! as! NSDictionary)["age"] as! String
self.gender = (snapShot.value! as! NSDictionary)["gender"] as! String
self.description = (snapShot.value! as! NSDictionary)["description"] as! String
self.hair = (snapShot.value! as! NSDictionary)["hair"] as! String
self.skin = (snapShot.value! as! NSDictionary)["skin"] as! String
self.tel = (snapShot.value! as! NSDictionary)["tel"] as! String
}
func toAnyObject() -> [String: Any]{
return ["name": name, "age": age, "gender": gender, "description": description, "hair": hair, "skin": skin, "tel": tel]
}
}
This is my fetch code:
ref.child("users").observe(.childAdded, with: { (snapshot) in
if(snapshot.value is NSNull){
}else{
let user = User(snapShot: snapshot)
print("snapshot not nil: \(snapshot.key) \(snapshot.value)")
print("user: \(user.name)")
}
It will have some data empty, like skin and description, see? I have some register with less keys, in android this is ok, but on swift it cant handle nil
The first register works ok, but the second crash My data base
fatal error: unexpectedly found nil while unwrapping an Optional value 2016-12-21 14:13:46.765206 GPMap[6033:1579494] fatal error: unexpectedly found nil while unwrapping an Optional value