使用Firebase快速接收所有帖子时遇到问题。
我想遍历并获取发布了帖子的所有用户的所有imageURL值。
Post-> userID-> PostKey-> imageURl
这是我一直试图检索这些值但无济于事的代码。
var ref: DatabaseReference!
ref = Database.database().reference()
let postsRef = ref.child("posts")
postsRef.observeSingleEvent(of: .value) { (snapshot) in
if snapshot.exists() {
for child in snapshot.children { //.value can return more than 1 match
let snap = child as! DataSnapshot
let dict = snap.value as! [String: Any]
let myPostURL = dict["imageURL"] as! String
print("POST URL: " + myPostURL)
}
} else {
print("no user posts found")
}
}
答案 0 :(得分:2)
您的ref
变量指向posts
节点:
let postsRef = ref.child("posts")
然后,您检索该节点的值,并遍历其子节点:
postsRef.observeSingleEvent(of: .value) { (snapshot) in
if snapshot.exists() {
for child in snapshot.children {
这意味着child
是xPCdfc5d...Oms2
的快照。然后,您将获得有关该子快照的属性的字典,并在其中打印imageURL
属性:
let snap = child as! DataSnapshot
let dict = snap.value as! [String: Any]
let myPostURL = dict["imageURL"] as! String
print("POST URL: " + myPostURL)
但是,如果您密切关注JSON,则xPCdfc5d...Oms2
节点将没有属性imageURL
。
您在posts
下有两个动态级别,因此您需要在值上进行两个嵌套循环:
postsRef.observeSingleEvent(of: .value) { (snapshot) in
if snapshot.exists() {
for userSnapshot in snapshot.children {
let userSnap = userSnapshot as! DataSnapshot
for childSnapshot in userSnap.children {
let childSnap = childSnapshot as! DataSnapshot
let dict = childSnap.value as! [String: Any]
let myPostURL = dict["imageURL"] as! String
print("POST URL: " + myPostURL)
}
}
}
}