如何遍历实际上是对象的 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.value和 first sample in the Firebase documentation on reading data .
关于ios - 如何循环遍历 Firebase 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49354469/