Firebase Access Snapshot Error in Swift 3

I recently upgraded to fast 3 and got an error while trying to access some things from the snapshot. Observe the meaning of the event.

My code is:

ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in

    let username = snapshot.value!["fullName"] as! String
    let homeAddress = snapshot.value!["homeAddress"] as! [Double]
    let email = snapshot.value!["email"] as! String
}

Error around three of the above variables and states:

The type "Any" has no substring elements

Any help would be greatly appreciated

+4
source share
2 answers

I think you probably need to give back snapshot.valuehow NSDictionary.

ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in

    let value = snapshot.value as? NSDictionary

    let username = value?["fullName"] as? String ?? ""
    let homeAddress = value?["homeAddress"] as? [Double] ?? []
    let email = value?["email"] as? String ?? ""

}

You can see the firebase documentation: https://firebase.google.com/docs/database/ios/read-and-write

+11
source

Firebase , snapshot.value Any?, , , , . , snapshot.value Int .

, Firebase JSON-; /, snapshot.value , .

ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in

    if let firebaseDic = snapshot.value as? [String: AnyObject] // unwrap it since its an optional
    {
       let username = firebaseDic["fullName"] as! String
       let homeAddress = firebaseDic["homeAddress"] as! [Double]
       let email = firebaseDic["email"] as! String

    }
    else
    {
      print("Error retrieving FrB data") // snapshot value is nil
    }
}
+8

Source: https://habr.com/ru/post/1660601/


All Articles