Swift 从firebase获取相对于用户uid的用户名以显示注释

Swift 从firebase获取相对于用户uid的用户名以显示注释,swift,xcode,firebase,Swift,Xcode,Firebase,我正在创建保存注释的集合视图,从Firebase中获取注释、注释id、帖子id和用户uid。当我尝试获取与用户uid相关的用户详细信息并附加注释时,它不起作用。我想这是因为我在用户引用中添加了snapshot.value,因此它不再有注释引用。如何获取注释和与UID相关的用户名,并将其显示在comments集合视图中 以下是Firebase中的层次结构: 在我的view post controller中,我获取的注释如下所示 var comments = [Comment]() filep

我正在创建保存注释的集合视图,从Firebase中获取注释、注释id、帖子id和用户uid。当我尝试获取与用户uid相关的用户详细信息并附加注释时,它不起作用。我想这是因为我在用户引用中添加了snapshot.value,因此它不再有注释引用。如何获取注释和与UID相关的用户名,并将其显示在comments集合视图中

以下是Firebase中的层次结构:

在我的view post controller中,我获取的注释如下所示

  var comments = [Comment]()
fileprivate func fetchComments() {
    guard let postID = self.post?.id else {return}
    let commentRef = Database.database().reference().child("comments").child(postID)
    commentRef.observe(.childAdded, with: { (snapshot) in

        guard let dict = snapshot.value as? [String: Any] else {return}

        guard let uid = dict["uid"] as? String else {return}

        let userRef = Database.database().reference().child("users/\(uid)/profile")
        userRef.observe(.value, with: { snapshot in

            if (snapshot.value as? [String: Any]) != nil {
                //let snap = snapshot.value as? [String: Any]
                var comment = Comment(dictionary: dict)


                comment.user = snapshot.value as? User
                self.comments.append(comment)
                print(comment)
                self.commentCollectionView.reloadData()
                }
            })

        })
}
像这样设置注释的集合视图

extension ViewPostViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return comments.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "commentCell", for: indexPath) as! CommentCollectionViewCell
    cell.comment = self.comments[indexPath.item]
    return cell
}
}
My CommentsCollectionViewCell.swift具有以下代码:

class CommentCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var commentLabel: UILabel!
@IBOutlet weak var timePostedLabel: UILabel!

var comment: Comment? {
    didSet {
        guard let comment = comment else {return}
        guard let username = comment.user?.username else {return}
        print(username)
        commentLabel.text = comment.comment
        usernameLabel.text = comment.user?.username
    }
}
}
struct Comment {

var user: User?

let comment: String

let uid: String

init(dictionary: [String: Any]) {
    self.comment = dictionary["comment"] as? String ?? ""
    self.uid = dictionary["uid"] as? String ?? ""
}
}
comments模型类具有以下代码:

class CommentCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var commentLabel: UILabel!
@IBOutlet weak var timePostedLabel: UILabel!

var comment: Comment? {
    didSet {
        guard let comment = comment else {return}
        guard let username = comment.user?.username else {return}
        print(username)
        commentLabel.text = comment.comment
        usernameLabel.text = comment.user?.username
    }
}
}
struct Comment {

var user: User?

let comment: String

let uid: String

init(dictionary: [String: Any]) {
    self.comment = dictionary["comment"] as? String ?? ""
    self.uid = dictionary["uid"] as? String ?? ""
}
}

首先,我将重构您的代码,将用户名包含在注释桶中,以节省您在设备上的工作量,以便稍后从多个源中提取它

这很容易解决。在
saveToFirebase
函数中添加一行或两行代码,在
fetchComments
函数中添加一行或两行代码

但是如果你想保持它的结构,我会做如下的事情:

func getComments(_ post: String, completion:  @escaping (_ info: [String?], _ error: NSError?) -> Void)  { 
    Database.database().reference.child("comments").child(postID).observeSingleEvent(of: .value) { (snapshot) in
        if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
            for snap in snapshot {
                if let dict = snap.value as? Dictionary<String, AnyObject> {
                    completion([dict["comment"],dict["uid"]],nil) // send data through handler
                } else { completion([], someError) }
            }
        } else { completion([], someError) }
    }
}


func getUserName(_ uid: String, completion:  @escaping (_ info: [String: Any]?, _ error: NSError?) -> Void)  { 
    Database.database().reference.child("users").child(uid).observeSingleEvent(of: .value) { (snapshot) in
        completion([snapshot],nil) // send data back
    } 
}

再次阅读后,我意识到我误解了你的问题,并更新了答案。