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

时间:2018-05-03 16:21:21

标签: swift xcode firebase

我正在创建包含评论的集合视图,我从Firebase获取评论,评论ID,帖子ID和用户uid。当我尝试获取与用户uid相关的用户详细信息并附加注释时,它不起作用。我认为这是因为我将snapshot.value附加到用户引用中,因此它不再具有注释引用。如何获取评论和与UID相关的用户名并将其显示在评论集合视图中?

以下是Firebase中的层次结构: Click here.

在我的视频帖子控制器中,我正在提取这样的评论。

  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
}
}

我的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 ?? ""
}
}

1 个答案:

答案 0 :(得分:0)

首先,我会重构您的代码,将用户名包含在评论桶中,以节省您在设备上工作的负担,以便以后从多个来源中提取。

这很容易解决。在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
    } 
}

然后在您的collectionView内部设置内容时,您可以调用这样的功能:

        // or wherever you get your postID's from
getComments(posts[indexPath.row], completion: { (info, err) in 
    if err != nil { 
        print(err!.localizedDescription) 
    } else { 
        // info is available find user
        guard let uid = info[1] as? String? else { return }
        // do whatever else you want to with the info here 
        // like populate cell data (perform on main thread)
        getUserName(uid, completion: { (snapDict, err) in
            if err != nil {
                // handle error
            } else {
                // get Username from dictionary and do what you want with it
        }) // end getUserName
    } 
}) // end getComments