ios - 检查 firebase 快照是否等于文本字段输入

标签 ios swift firebase firebase-realtime-database

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

"Snap (locations) null"

即使我输入一个我知道在数据库中的值。非常感谢您的帮助:-) 下面是我的 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")
            }
    })
}

最佳答案

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

{
"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”的子项,因此任何值都不会与您要查找的值相匹配。由于您希望地址与 child 的 key 相匹配,因此我们无需查询即可获取该 child 的数据。我们可以观察确切的路径,像这样:

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

关于ios - 检查 firebase 快照是否等于文本字段输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51529448/

相关文章:

ios - iOS AVFoundation导出 session 缺少音频

ios - 将 UITableView 部分与 Web 服务分组

ios - 带有垂直标题的 UICollectionView 水平滚动

ios - 如何用另一个值替换不断变化的数组?

swift - 使用创建字典编译 Swift 源文件问题

javascript - Firebase Firestore - 查询大集合中的帖子,其中 groupId 应与数组中的值匹配

Firebase 托管 : unable to get local issuer certificate

ios - 使用一组图像制作动画时,我应该考虑 iPad 4 的哪些限制?

ios - 将 NSString 转换为字符数组

firebase - 异步 new Vue() 等待初始身份验证