Basil Basil - 1 year ago 92
Swift Question

How To Search in Database Firebase

I did my search on Stackoverflow but I didn't find the solution I'm looking for

I want to search in database firebase if The "Name" is equal to The name in Navigation Title and also the "Email" that user use to signIn is equal to The Email in Database then it will avoid user to add new item

The Json looks like this

"Items" : {
"-KUMSKLFqMjclbqygnPL" : {
"Item" : "asdfg"
"Name" : "Fadi”,
"User Email" : ""

My code is

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

var NAME : String!
var UserEmail : String!
var email : String!

databaseRef.child("Items").queryOrderedByKey().observe(.childAdded, with: { snapshot in

let snapshotValue = snapshot.value as? NSDictionary
NAME = (snapshotValue?["Name"] as? String)!

UserEmail = (snapshotValue?["User Email"] as? String)!
email = (FIRAuth.auth()?.currentUser?.email)!

if NAME == navigationItem.title {

if UserEmail == email {
print ("you can't add new item \(UserEmail)")
}else if UserEmail != email {
print("you can add new Item")


My problem is If there is name equal Fadi but there are two different emails
The result will be

you can't add new item Optional("")
you can add new Item

It should print only

you can't add new item Optional("")

I don't know how to Break it , Right now it's looks like it looping through all database

Updated :

I try the Dravidian answer

Result of print(snapShot.value) :

"-KUMS7J-rCglHrVGX840" = {
"Item" = "asdsd"
"Name" = "a";
"User Email" = "";

The result is right! but now I need to extract User Email from that node

Answer Source

If you are looking for finding the node which has a specific name try this:-

  let databaseRef = FIRDatabase.database().reference()
  databaseRef.child("Items").queryOrdered(byChild: "Name").queryEqual(toValue: "Fadi").observeSingleEvent(of: .value, with: { (snapShot) in

        if let snapDict = snapShot.value as? [String:AnyObject]{

              for each in snapDict{
                      let key  = each.key as! String
                      let name = each.value["Name"] as! String
        }, withCancel: {(Err) in


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download