使用Swift在Firebase中获取嵌套数据

时间:2018-11-17 20:17:08

标签: swift firebase firebase-realtime-database

我正在尝试对我的应用程序中的帖子实施评论,但是在帖子中获取称为“评论”的嵌套数据有困难。如果我的Firebase数据库结构如图所示,如何正确地将注释作为messageComments数组下载?

func getFeedMessages(handler: @escaping (_ feedMessages:[FeedMessages]) -> ()){
        var feedMessagesArray = [FeedMessages]()
        var commentArray = [messageComments]()


        REF_FEEDMESSAGES.observeSingleEvent(of: .value) { (feedMessagesSnapshot) in

            guard let feedMessagesSnapshot = feedMessagesSnapshot.children.allObjects as? [DataSnapshot] else {return}
            for messages in feedMessagesSnapshot {

                let content = messages.childSnapshot(forPath: "content").value as? String ?? "Joe Flacco is an elite QB"
                let icon = messages.childSnapshot(forPath: "icon").value as? String ?? "none"
                let color = messages.childSnapshot(forPath: "color").value as? String ?? "bop"
                let date = messages.childSnapshot(forPath: "date").value as? String ?? "0"
                let comments = messages.childSnapshot(forPath: "comments").value as? [messageComments] ?? []
                let userName = messages.childSnapshot(forPath: "userName").value as? String ?? "Anonymous"

                let messages = FeedMessages(content: content, color: color, icon: icon, date: date, comments: comments, userName: userName)
                feedMessagesArray.append(messages)
            }

            handler(feedMessagesArray)
        }
    }

enter image description here

2 个答案:

答案 0 :(得分:1)

您无法访问此类评论。您需要使用encodable来执行此操作,或者由于您正在手动访问每个快照中的值,因此可以像这样访问它:

let comments = messages.childSnapshot(forPath: "comments").value as? [String: Any]
let comment1 = comments?["comment1"] as? String ?? "comment1"
let comment2 = comments?["comment2"] as? String ?? "comment2"

然后,您通常需要通过调用messageComments初始化程序来初始化对象messageComments。另外,我建议您以大写字母开头您的班级名称。

编辑:要手动加载评论,我建议这样做:

if let comments = comments { 
    for comment in comments.values {
       // here your access your comment as you want, you need to cast as string
    }
}

答案 1 :(得分:0)

这是解决方法

let comments = messages.childSnapshot(forPath: "comments").value as? [String: Any] ?? [:]



                for comment in comments {

                    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 ?? ""
                    let theName = theComment?["userName"] as? String ?? ""

                    let aComment = messageComments(content: theContent, color: theColor, icon: theIcon, date: theDate,  userName: theName)
                    commentArray.append(aComment)
                }