简体   繁体   English

Swift Firebase在儿童中获得价值

[英]Swift Firebase get values in children

Im having issues receiving all posts using firebase for swift. 我在使用Firebase快速接收所有帖子时遇到问题。

I want to loop through and get all imageURL values for all users that have made a post. 我想遍历并获取发布帖子的所有用户的所有imageURL值。

Post->userID->PostKey->imageURl Post->用户ID-> PostKey-> imageURl

This is the code ive been trying to use to retrieve these values but to no avail. 这是我一直试图检索这些值但无济于事的代码。

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

在此处输入图片说明

Your ref variable points to the posts node: 您的ref变量指向posts节点:

let postsRef = ref.child("posts")

Then you retrieve the value of that node, and loop over its children: 然后,您检索该节点的值,并遍历其子节点:

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

That means that child is a snapshot of xPCdfc5d...Oms2 . 这意味着childxPCdfc5d...Oms2的快照。 You then get a dictionary of the properties of this child snapshot and print the imageURL property in there: 然后,您将获得此子快照的属性的字典,并在其中打印imageURL属性:

            let snap = child as! DataSnapshot
            let dict = snap.value as! [String: Any]
            let myPostURL = dict["imageURL"] as! String
            print("POST URL: " + myPostURL)

But if you follow along closely in your JSON, the xPCdfc5d...Oms2 node doesn't have a property imageURL . 但是,如果您严格遵循JSON,则xPCdfc5d...Oms2节点将没有属性imageURL

You have two dynamic levels under posts , so you need two nested loops over the value: 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)
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM