gpt4 book ai didi

swift - 从firebase中获取相对于用户uid的用户名以显示评论

转载 作者:行者123 更新时间:2023-11-30 11:32:03 26 4
gpt4 key购买 nike

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

Firebase 中的层次结构如下所示: Click here.

在我的 View 帖子 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()
}
})

})
}

像这样设置评论的 Collection View 。

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

最佳答案

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

这很容易解决。将一两行代码添加到您的 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

关于swift - 从firebase中获取相对于用户uid的用户名以显示评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50159734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com