检查Firebase快照是否等于文本字段输入

时间:2018-07-26 00:39:03

标签: ios swift firebase firebase-realtime-database

我正在尝试检查文本输入是否等于firebase数据库中的值。我遇到错误

  

“捕捉(位置)为空”

即使我输入一个我知道在数据库中的值也是如此。我非常感谢您的帮助:-)以下是我的JSON文件。

{
"locations" : {
"115 W Perry Carriage House" : {
  "City" : "Savannah",
  "State" : "GA",
  "img" : " "
},
"115 W Perry Street" : {
  "City" : "Savannah",
  "State" : "GA",
  "img" : " "
},
"117 West Charlton Street" : {
  "City" : "Savannah",
  "State" : "GA",
  "img" : " "
},
"127 Coming Street Unit C" : {
  "City" : "Charleston",
  "State" : "SC",
  "img" : " "

和代码:

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

    databaseRef.child("locations")
      .queryOrdered(byChild: "locations")
      .queryStarting(atValue: addressTextField.text)
      .observe(DataEventType.value, with: 
    { 
        (snapshot) in
        print(snapshot)
            if snapshot.exists(){
                print("Address is in DB")
            }else{
                print("Address doesn't exist")
            }
    })
}

2 个答案:

答案 0 :(得分:1)

该代码当前在您的问题中使用的查询正在查看嵌套在“位置”下的名为“位置”的子代的值。因此,如果您想象查询在寻找数据,它将在这里拉第一个孩子,而不是第二个。

{
"locations" : {
  "115 W Perry Carriage House" : {
    "locations": "115 W Perry Carriage House", // <- here's one!
    "City" : "Savannah",
    "State" : "GA",
    "img" : " "
  },
  "115 W Perry Street" : { // <- hmm...this one doesn't have "locations"
    "City" : "Savannah", 
    "State" : "GA",
    "img" : " "
  },
  //...
}

由于数据结构不包含任何称为“ locations”的子项,因此不会有任何值与您要查找的子项匹配。由于您希望地址与子项的键匹配,因此我们无需查询即可获取该子项的数据。我们可以观察到确切的路径,如下所示:

let databaseRef = Database.database().reference()
guard let text = addressTextField.text else { return }
databaseRef.child("locations/\(text)")
  .observe(.value, with:  { (snapshot) in
    print(snapshot)
    if snapshot.exists() {
      print("Address is in DB")
    } else {
      print("Address doesn't exist")
    }
})

答案 1 :(得分:0)

您要过滤的值是节点的。因此,您需要致电queryOrderedByKey()。像这样:

databaseRef.child("locations")
  .queryOrderedByKey()
  .queryStarting(atValue: addressTextField.text)
  .observe(DataEventType.value, with: 
{ 
  ...