首页 > 解决方案 > 检查firebase快照是否等于文本字段输入

问题描述

我正在尝试检查文本输入是否等于 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")
            }
    })
}

标签: iosswiftfirebasefirebase-realtime-database

解决方案


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

{
"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" : " "
  },
  //...
}

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

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

推荐阅读