Read data from firebase swift

2020-06-06 05:17发布

问题:

I'm trying to retrieve data from firebase database, but when I run the code it display nothing, though no errors shown

I got this piece of code from Firebase manual, by the way, I'm pretty sure that the path is correct

let ref = FIRDatabase.database().reference()

ref.child("users").child("user").child(username).observeSingleEvent(of: .value, with: { (snapshot) in
        // Get user value
        let value = snapshot.value as? NSDictionary
        let score = value?["score"] as? String ?? ""
        print(score)

        // ...
    }) { (error) in
            print(error.localizedDescription)
}

JSON

{
  "users" : {
    "user" : {
      "e1410kokeZS8xv81J1RzhN4V2852" : {
        "email" : "aaaa@gmail.com",
        "score" : 0,
        "username" : "Afnan"
      },
      "jPx8XJ3Q9AazDM7qIOhz02PBfh22" : {
        "email" : "aaaa@ggg.com",
        "score" : 13,
        "username" : "ghhh"
      }
    }
  }
}

回答1:

You are listening for the .value event, but your block is dealing with a single item at a time so use .childAdded event for that.

let ref = FIRDatabase.database().reference().child("users").child("user").child(username)

ref.observeSingleEvent(of: .childAdded, with: { (snapshot) in
     if let userDict = snapshot.value as? [String:Any] {
          //Do not cast print it directly may be score is Int not string
          print(userDict["score"]) 
     }
}

Note: In Swift use native Dictionary instead of NSDictionary