【问题标题】:Swift Firebase get values in childrenSwift Firebase 在孩子中获取价值
【发布时间】:2019-06-03 02:55:57
【问题描述】:

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

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

    您的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)
                }
            }
        }
    }
    

    【讨论】:

    • 完美运行!感谢您的帮助和解释!
    猜你喜欢
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多