0

I want to look through Firebase and check if a certain value for a child exists and if that value does not exist. I want to print out a statement

 databaseRef.child("books").queryOrdered(byChild: "Category").queryEqual(toValue: categorySegue).observe(.childAdded, with: { (snapshot) in

            if snapshot.exists() {
                print("data found")
            }else{
                print("no data found")
            }
})

When the child value exists, it prints out data found perfectly fine but when it does not exist. It does not print out no data found

juelizabeth
  • 485
  • 1
  • 8
  • 31

1 Answers1

1

That's because you're observing .childAdded, which only fires if there is a child matching your query.

If you want to also detect the situation when no child matches, you'll need to observe the .value event and loop over the results.

databaseRef.child("books").queryOrdered(byChild: "Category").queryEqual(toValue: categorySegue).observe(.childAdded, with: { (snapshot) in

    if snapshot.exists() {
        print("data found")
        for child in snapshot.children {
            print(child.key)
        }
    }else{
        print("no data found")
    }

})

Also see Searching through child values Firebase / Swift

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807