如何在数据库Firebase中搜索

时间:2016-10-22 17:20:48

标签: swift firebase firebase-realtime-database

我在Stackoverflow上搜索了但是我找不到我正在寻找的解决方案

我想在数据库firebase中搜索" Name"等于导航标题中的名称以及"电子邮件"用户使用signIn等于数据库中的电子邮件然后它将避免用户添加新项目

Json看起来像这样

"Items" : {
      "-KUMSKLFqMjclbqygnPL" : {
      "Item" : "asdfg"
      "Name" : "Fadi”,
      "User Email" : "i@i.com"
      }
    }

我的代码是

    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")

            }
       }
    })

我的问题是如果名称等于Fadi但有两个不同的电子邮件 结果将是

you can't add new item Optional("i@i.com")
you can add new Item

它应该只打印

you can't add new item Optional("i@i.com")

我不知道如何打破它,现在它看起来像是在循环遍历所有数据库

已更新

我尝试了Dravidian的回答

打印结果(snapShot.value):

    "-KUMS7J-rCglHrVGX840" =     {
    "Item" = "asdsd"            
    "Name" = "a";
    "User Email" = "a@a.com";
    };

结果是对的!但现在我需要从该节点提取用户电子邮件

1 个答案:

答案 0 :(得分:4)

如果您正在寻找具有特定名称的节点,请尝试以下方法: -

  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
                      print(key)
                      print(name)
                 }
            }
        }, withCancel: {(Err) in

            print(Err.localizedDescription)

    })