Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Accessing Snapshot Value Error in Swift 3

I recently upgraded to swift 3 and have been getting an error when trying to access certain things from a snapshot observe event value.

My code:

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
}

The error is around the three variables stated above and states:

Type 'Any' has no subscript members

Any help would be much appreciated

like image 813
Rohan Vasishth Avatar asked Nov 12 '16 20:11

Rohan Vasishth


2 Answers

I think that you probably need to cast your snapshot.value as a 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 take a look on firebase documentation: https://firebase.google.com/docs/database/ios/read-and-write

like image 70
Raul Marques Avatar answered Nov 01 '22 13:11

Raul Marques


When Firebase returns data, snapshot.value is of type Any? so as you as the developer can choose to cast it to whatever data type you desire. This means that snapshot.value can be anything from a simple Int to even function types.

Since we know that Firebase Database uses a JSON-tree; pretty much key/value pairing, then you need to cast your snapshot.value to a dictionary as shown below.

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
    }
}
like image 42
eshirima Avatar answered Nov 01 '22 12:11

eshirima