首页 > 解决方案 > 查看嵌套节点中的评论 (Firebase)

问题描述

我的应用程序上有一个评论页面。当用户输入评论并点击回复按钮时,他们的评论将保存到 firebase 数据库中。请参阅下面的 Firebase 结构。我遇到的问题是,当我尝试查看评论时,表格视图是空白的,即使评论正确保存在 firebase 中也不会显示任何评论。

我不知道我的 observeComments() 函数是否不完整,因此无法正确加载评论?

Firebase 数据库

var comments = [Comments]()   

func obeserveComments() {

    let postRef = Database.database().reference().child("posts")
    
    var tempComments = [Comments]()
    
    postRef.observe(.value, with: { snapshot in
        for child in snapshot.children{
            if let childSnapshot = child as? DataSnapshot,
               let dict = childSnapshot.value as? [String:Any],
               let comments = dict["comments"] as? [String:Any],
                let degree = comments["reply degree"] as? String,
                let name = comments["reply name"]as? String,
                let text = comments["reply text"]as? String,
                let university = comments["reply university"]as? String,
                let photoURL = comments["reply url"]as? String,
                let url = URL(string: photoURL),
                let timestamp = comments["timestamp"] as? Double {
               
                let comment = Comments(id: childSnapshot.key, fullname: name, commentText: text, university: university, degree: degree, photoURL: photoURL, url: url, timestamp: timestamp)
                
                tempComments.append(comment)
                
            }
        }
        
        self.comments = tempComments
        self.tableView.reloadData()
        
    })
}

  @IBAction func ReplyTapped(_ sender: Any) {
    // fetch the current user data from firebase
    let uid = Auth.auth().currentUser?.uid
    let database = Firestore.firestore()
    
    // get data from firestore
    let docRef = database.collection("users").document(uid!)
    
    docRef.addSnapshotListener { snapshot, error in
        guard let document = snapshot else {
            print("Error getting documents: \(String(describing: error))")
                return
            }
            let fullname = document.get("fullname") as? String
            let degree = document.get("degree") as? String
            let university = document.get("university") as? String
            let photoURL = document.get("photourl") as? String
    
        let commentReference = Database.database().reference().child("posts")
    
        let commentObject = ["reply text": self.ReplyComment.text!,"reply name":fullname! ,"reply degree": degree!, "reply university": university!,"reply url": photoURL!, "timestamp": [".sv":"timestamp"]] as [String : Any]
        
            //get the key for the exact post that comment is added
            let key =  self.keyFound
        
            // post comment and save it to database
            commentReference.child(key).child("comments").childByAutoId().updateChildValues(commentObject, withCompletionBlock: { error, ref in
                        if error == nil{
                            // clear the text field
                            self.ReplyComment.text = ""
                        } else {
                            // handle the error
                        }
    })
}
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return comments.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCell(withIdentifier: "commentCell", for: indexPath) as! CommentsTableViewCell
    cell.set(comments: comments[indexPath.row])
    cell.selectionStyle = .none
    return cell

}

标签: jsonswiftfirebase-realtime-database

解决方案


推荐阅读