ios - 如何循环遍历 Firebase 数据

标签 ios swift firebase firebase-realtime-database

如何遍历实际上是对象的 Firebase 数据(子数据)并在 Swift 4 中访问它们的属性?

作为 Swift 的初学者,我试图循环访问从 Firebase 检索的数据,并尝试访问这些对象的属性。看起来要复杂得多,然后应该很快(只是我的主观意见)

根据 Firebase site 上的文档这就是我的

_commentsRef.observe(.value) { snapshot in
    for child in snapshot.children {
        // Access to childs here ...
    }
}

现在,结合上面的内容以及我在网上找到的教程和解释(顺便说一句,我找不到能完全解释这一点的),这就是我所拥有的:

ref.child("activities").child("list").observeSingleEvent(of: .value, with: { (snapshot) in
    // The list i got here is the list of the childs which are objects
    // Lets loop through that list and pull properties we need
    for child in snapshot.children.allObjects as! [DataSnapshot] {
        print(child.value)
    }
})

循环中的打印将正确显示对象及其所有属性,但我无法访问这些属性。 使用“child.value.title”之类的内容访问它会导致错误“‘Any’类型的值没有成员‘title’”

我是否需要将 child.value 转换为其他内容,也许将其强制转换或以某种方式将其转换为属性可访问的 JSON 或类似的东西?

最佳答案

如果您在包含多个属性的快照上调用 value,您返回的是一个以属性名称作为键的 NSDictionary。因此,要获取 title 键的值,您需要执行以下操作:

for child in snapshot.children.allObjects as! [DataSnapshot] {
    print(child.value)
    let dict = child.value as? [String : AnyObject] ?? [:]
    print(dict["title"])
}

或者,您可以使用 DataSnapshot 的其他成员导航到 title 属性,然后对其调用 .value:

for child in snapshot.children.allObjects as! [DataSnapshot] {
    print(child.value)
    print(child.childSnapshot(forPath: "title").value)
}

参见 DataSnapshot.valuefirst sample in the Firebase documentation on reading data .

关于ios - 如何循环遍历 Firebase 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49354469/

相关文章:

ios - Swift 2 reloadData 向 UICollectionView 添加了更多单元格

ios - 使用 AutoLayout 设计简单的应用程序

ios - 两个堆栈 View 中多行 View 的自动布局问题

iphone - 守卫 Malloc 不起作用

ios - 在第二个 SIAlertView 消息和 popViewController 之后屏幕锁定

ios - 仅在首次初始化自定义 UIView 时如何在 LayoutSubviews 中执行代码

angular - Firebase Firestore - 限制用户可以创建的产品文档数量

firebase - Firebase 托管的 Flutter Web/Dart CORS 错误

node.js - 使用适用于 iOS 应用的 Firebase、Node.js 和 Google Cloud Messaging 推送通知

ios - 无法推送到 iOS 中的 View Controller