ios - 在 firebase Root 上的 IndexOn 查询整个数据库 swift 3

标签 ios swift firebase firebase-realtime-database firebase-security

我正在尝试在 firebase 数据库中按名称查询,我想返回所有与查询匹配的名称。但我似乎无法让它工作,我收到错误消息 Consider adding ".indexOn": "name"at/to your security rules

安全规则:

{
  "rules": {
    ".read": "true",
    ".write": "true",
    "goals_new": {
      ".indexOn": ["name"]
    }
  }
}

我可以像这样检索特定 child 的名字:

let query = ref.child("goals_new").queryOrdered(byChild:"name").queryEqual(toValue: name)
    query.observe(.childAdded) { (snapshot) in

    //  if let values =
        if let values = snapshot.value as? [String:String] {
            print(values)
            print(values["name"]?.count ?? "")

        }
    }

但我想检索数据库中与查询匹配的所有名称

数据库结构:

"goals_new" : [ null, {
    "name" : "Eric thomas",
    "pic" : “…….”,
    "title" : "Be Obsessed with your Goals",
    "url" : “……”
  }, 
{
    "name" : "Bob Proctor",
    "pic" : “……….",
    "title" : "Goal Achievement System",
    "url" : “………”
  },

如有任何帮助,我们将不胜感激。

最佳答案

考虑在您的安全规则中添加 ".indexOn": "name"<- 只是一个警告,所以您不必太担心。

我看到了一个错误。看起来您正在使用数组来存储“goals_news”的对象,因为键是数字 1、2 等...也许这与您的查询有关,您必须像每次一样为字符串键更改它们添加一个使用 firebase 方法 childByAutoID()。

最好使用 .value 而不是 .childAdded 方法,这样您就可以获得与名称匹配的所有对象,如下所示:

      let query = ref.child("goals_new").queryOrdered(byChild:"name").queryEqual(toValue: name)
query.observe(.value) { (snapshot) in

    guard snapshot.exists() && snapshot.hasChildren() else {return}
    for snap in snapshot.children {
          var currentSnapValue = (snap as! DataSnapshot).value as! [String: String]
         print("Name: \(currentSnapValue["name"])")

    }
 }

这样你就得到了所有匹配名称的对象

关于ios - 在 firebase Root 上的 IndexOn 查询整个数据库 swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50296488/

相关文章:

ios - 进度 View 循环

swift - 在 ScrollView 中缩放图像

java - 查询Firestore数据并向与查询匹配的所有文档添加一个字段

ios - 如何从 UIScrollView 中删除 CAShapeLayer?

ios - 在后台应用程序无法运行时播放音频

ios - 使用反余弦的线之间的绝对角度

swift - 使用增量运算符会产生构建错误 "swift Unary operator '++' cannot be applied to an operand of type ' Int'"

ios - UITextView 的顶行有不同的文本颜色

swift - Xcode快速在Firebase数据更新上进行内存填充

Firebase Firestore 将时间戳作为空对象返回