【问题标题】:How to loop through Firebase data如何遍历 Firebase 数据
【发布时间】:2018-03-19 01:11:10
【问题描述】:

如何遍历实际上是对象的 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 或类似的东西?

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

    如果您在包含多个属性的快照上调用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

    【讨论】:

    • 第一个解决方案适用于“let dict = child.value as?[String : AnyObject] ?? [:]”。而不是它看起来的快照。在我的案例中,第二个解决方案是:“'DataSnapshot' 类型的值没有成员 'child'
    • 糟糕,我一直忘记它是 Swift 中的 childSnapshot(forPath:)。见firebase.google.com/docs/reference/swift/firebasedatabase/api/…。对此感到抱歉。
    • 确实它现在正在工作......再做一个更改,DataSnapshot 似乎不再是可选的,因此使用问号表示第二个解决方案失败。没有它可以正常工作。
    • 感谢您指出最后一个错误。我更新了答案中的代码。
    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 2018-02-26
    • 1970-01-01
    相关资源
    最近更新 更多