简体   繁体   中英

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

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

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM