fslee18
fslee18

Reputation: 1

I cannot retrieve data from Firebase database

I setup Firebase database like this:

dataS
- LjYal4ijEdjfafe
  - email: "[email protected]"
  - firstname: "aa"
  - lastname: "bb"

And I cannot retrieve data "lastname", it always return nil.

let ref = Database.database().reference()
ref.queryOrdered(byChild: "email").queryEqual(toValue: email1).observeSingleEvent(of: .value, with: { (snapshot) in
    if !snapshot.exists() {
        print("cannot find in firebase")
        return
    }

    let value1 = snapshot.value as? NSDictionary
    let lastnameP = value1?["lastname"] as? String ?? ""

    print(lastnameP)

Upvotes: 0

Views: 72

Answers (1)

Jay
Jay

Reputation: 35648

There are a few issues with the code.

The first is when observing by .value, all of the matches will be returned whether it be 1 or 1000 so that returned DataSnapshot will need to be iterated over to access the child data, even if there's 1. If using .childAdded, it will return one at a time in the snapshot if using .observe, and only the first using .childAdded.

Second thing is the reference is pointing at the root reference. It appears dataS may be a child of the root

root_firebase
   dataS
      uid
         email
         firstname
         lastname

if not, then keep in mind this code matches that structure.

Last thing is to make it more Swifty and use modern function calls and add a little error checking in case the lastname node is not found with the nodes being read.

let email1 = "email to query for"
let ref = Database.database().reference()
let nodeToQueryRef = ref.child("dataS")
nodeToQueryRef.queryOrdered(byChild: "email")
              .queryEqual(toValue: email1)
              .observeSingleEvent(of: .value, with: { snapshot in
    if snapshot.exists() == false {
        print("cannot find in firebase")
        return
    }

    let returnedSnapshotArray = snapshot.children.allObjects as! [DataSnapshot]
    for snap in returnedSnapshotArray {
        let key = snap.key
        let lastName = snap.childSnapshot(forPath: "lastname").value as? String ?? "No Last Name"
        print(key, lastName)
    }
})

Upvotes: 1

Related Questions