Swift Firebase在儿童中获得价值

时间:2019-06-03 02:55:57

标签: ios swift firebase firebase-realtime-database

使用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")
        }
    }

enter image description here

1 个答案:

答案 0 :(得分:2)

您的ref变量指向posts节点:

let postsRef = ref.child("posts")

然后,您检索该节点的值,并遍历其子节点:

postsRef.observeSingleEvent(of: .value) { (snapshot) in
    if snapshot.exists() {
        for child in snapshot.children {

这意味着childxPCdfc5d...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)
            }
        }
    }
}