首页 > 解决方案 > 从firebase数据库获取子值数组

问题描述

数据库结构

数据库结构

我正在尝试从评论中获取一组用户(字符串),但是由于它在我的数据库中有点深,所以遇到了麻烦,这是我尝试过的实现,它返回 0 作为计数。

REF_FEEDMESSAGES.child(messageKey).child("comments").observeSingleEvent(of: .value) { (commentSnapshot) in
            guard let commentSnapshot = commentSnapshot.children.allObjects as? [DataSnapshot] else {return}

            for comment in commentSnapshot {

                let theComment = comment.value as? [String: Any]

                let theContent = theComment?["content"] as? String ?? ""
                let theIcon = theComment?["icon"] as? String ?? ""
                let theColor = theComment?["color"] as? String ?? ""
                let theDate = theComment?["date"] as? String ?? "0"
                let theName = theComment?["userName"] as? String ?? ""
                let theVerified = theComment?["isVerified"] as? String ?? "no"
                let profileImageURL = theComment?["profileImageURL"] as? String ?? ""
                let postedBy = theComment?["postedBy"] as? String ?? ""
                let likes = theComment?["likes"] as? String ?? ""
                let key = comment.key

                let likers = comment.childSnapshot(forPath: "likedBy").value as? [String] ?? []
                print(likers.count)

标签: iosswiftfirebasefirebase-realtime-database

解决方案


guard let likers = comment.childSnapshot(forPath: "likedBy").children.allObjects as? [DataSnapshot] else {return}
                for like in likers {
                    let theLike = like.value as? [String:Any]
                    print(theLike!["user"] as? String ?? "")
                    commentLiked.append(theLike!["user"] as? String ?? "")
                }

推荐阅读