swift - 从 firebase 获取与用户 uid 相关的用户名以显示评论
问题描述
我正在创建包含评论的集合视图,我在其中从 Firebase 获取评论、评论 ID、帖子 ID 和用户 uid。当我尝试获取与用户 uid 相关的用户详细信息并附加评论时,它不起作用。我认为这是因为我在用户参考中附加了 snapshot.value,因此它不再有评论参考。如何获取评论以及与 UID 相关的用户名并将其显示在评论集合视图中?
Firebase 中的层次结构如下所示: 单击此处。
在我看来,后控制器,我正在获取这样的评论。
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 ?? ""
}
}
解决方案
首先,我将重构您的代码以将用户名包含在评论桶中,以节省您在设备上的工作量,以便稍后从多个来源中提取它。
这很容易解决。将一两行代码添加到您的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
推荐阅读
- cordova - 来自 PhotoGallery iOS13 的 UIWebView 输入视频
- css - 禁用按钮的 CSS 使用 :not() 排除某个类
- c# - 无法在进程 dll 模块的入口点写入 1 个字节
- javascript - 具有不同数组的 D3 行 .defined()
- python - 无法在 Django 模型中按名称访问实例变量
- php - 在 WooCommerce 中的价格之前添加正常价格
- view - SwiftUI:将 View 调整为内容大小
- go - 运行 Stellar Horizon 测试用例之前需要注意的事项
- sql - SQL Developer 更改特定列的日期格式
- javascript - 不确定这种格式的含义