【问题标题】:Get information no matter number of childs in Firebase (Swift)无论 Firebase 中的孩子有多少(Swift),都可以获取信息
【发布时间】:2016-07-25 08:21:51
【问题描述】:

这是我的树:

我想获取d 值("its d"

但我没有打印任何信息

ref.queryOrderedByChild("userA")
            .observeSingleEventOfType(.Value, withBlock: { (snapshot) in
                if snapshot.exists() {
                    for child in (snapshot.value?.allValues)! {
                        if let fruits = child["c"] as? [String:String]{
                            let name = fruits["d"]
                            print(name)
                            }
                    }

【问题讨论】:

  • 你能解释更多吗...我不明白“无论 Firebase 中有多少孩子”这个词...
  • @EICaptainv2.0 这意味着例如我有 200 个孩子,我想获得最后一个孩子的价值
  • 我认为这种结构不可能......你需要通过那个键来获得最后一个值......
  • @EICaptainv2.0 好的,谢谢

标签: ios swift xcode firebase firebase-realtime-database


【解决方案1】:

这是特定问题的答案:

无论 Firebase 中有多少孩子,都可以获取信息

但不确定它是否是您正在寻找的。​​p>

要获得“d”,您不需要查询。您可以直接访问该数据。

这是我的结构(与你的匹配)

"the_users" : {
    "a" : {
      "b" : {
        "c" : {
          "d" : "It's d"
        }
      }
    }
  }

以及获取“d”值的代码

let theUsersRef = rootRef.child("the_users")
let dRef = theUsersRef.child("a/b/c/d")
dRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
     let msg = snapshot.value as! String
     print(msg)
})

和输出

It's d

【讨论】:

    【解决方案2】:

    当您调用queryOrderedByChild("userA") 时,它会告诉数据库按userA 属性的原始值排序。由于在您的 JSON 中没有具有原始值的 userA 属性,因此 order by 语句没有意义。

    您不会过滤查询中的数据,因此您将在附加侦听器的位置获得包含所有数据的快照。从您的代码示例中不清楚这是什么位置,但很可能它在 JSON 树中高于子 c 存在的位置。所以这意味着你没有打印任何名字。

    如果你简单地打印所有孩子可能会更清楚:

    ref.queryOrderedByChild("userA")
       .observeSingleEventOfType(.Value, withBlock: { (snapshot) in
           if snapshot.exists() {
               for child in (snapshot.value?.allValues)! {
                   print(child.key)
                   if let fruits = child["c"] as? [String:String]{
                       let name = fruits["d"]
                       print(name)
                   }
               }
           }
       })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多