如何在 firebase swift 中获取嵌套分支的值
How to get value of nested branch in firebase swift
我刚开始设置 firebase 的实时数据库,我正在尝试访问消息中的内容以显示在应用程序中。
这是我的数据库的结构:
我想访问“numberofresponses”值最小的每条消息的“内容”。
let ref: DatabaseReference! = Database.database().reference(withPath: "messagepool")
ref.queryOrdered(byChild: "numberofresponses").observeSingleEvent(of: .value, with: { snapshot in
if !snapshot.exists() {
print("no snapshot exists")
return }
print(snapshot)
上面的代码正确地打印了“消息池”,但我想要每个分支的具体内容值。我似乎错过了什么。这样做的正确方法是什么?谢谢
当您对 Firebase 数据库执行查询时,可能会有多个结果。所以快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果的列表。
因此,在您的 closure/completion 处理程序中,您将需要遍历 snapshot.children
以获取单个结果快照:
ref.queryOrdered(byChild: "numberofresponses").observeSingleEvent(of: .value, with: { snapshot in
if !snapshot.exists() {
print("no snapshot exists")
return
}
for childSnapshot in querySnapShot.children.allObjects as! [DataSnapshot] {
print(childSnapshot.key)
print(childSnapshot.value)
guard let value = childSnapshot.value as? [String: Any] else { return }
do {
guard let content = value["content"] as? String,
...
}
}
}
另见:
我刚开始设置 firebase 的实时数据库,我正在尝试访问消息中的内容以显示在应用程序中。
这是我的数据库的结构:
我想访问“numberofresponses”值最小的每条消息的“内容”。
let ref: DatabaseReference! = Database.database().reference(withPath: "messagepool")
ref.queryOrdered(byChild: "numberofresponses").observeSingleEvent(of: .value, with: { snapshot in
if !snapshot.exists() {
print("no snapshot exists")
return }
print(snapshot)
上面的代码正确地打印了“消息池”,但我想要每个分支的具体内容值。我似乎错过了什么。这样做的正确方法是什么?谢谢
当您对 Firebase 数据库执行查询时,可能会有多个结果。所以快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果的列表。
因此,在您的 closure/completion 处理程序中,您将需要遍历 snapshot.children
以获取单个结果快照:
ref.queryOrdered(byChild: "numberofresponses").observeSingleEvent(of: .value, with: { snapshot in
if !snapshot.exists() {
print("no snapshot exists")
return
}
for childSnapshot in querySnapShot.children.allObjects as! [DataSnapshot] {
print(childSnapshot.key)
print(childSnapshot.value)
guard let value = childSnapshot.value as? [String: Any] else { return }
do {
guard let content = value["content"] as? String,
...
}
}
}
另见: