我正在尝试使用名为“喜欢数”的标签来显示每张照片的喜欢数。我可以在Firebase中显示它,但是不能在UI中显示它。
在我的帖子模型中,我有
var likes: Int!
var hasLiked = false
然后在我的供稿单元中,尝试获取喜欢的数目并将其添加到我的标签上,称为“喜欢的数目”
guard let likes = posts?.likes else { return }
numberOfLikes.text = "\(likes) likes"
到目前为止,我所得到的与我喜欢的函数有关的信息...
guard let uid = Auth.auth().currentUser?.uid else {return}
// like and unlike
let values = [uid: post.hasLiked == true ? 0 : 1]
Database.database().reference().child("likes").child(postId).updateChildValues(values) { (error, _) in
if let error = error {
print("Failed to like post:", error)
return
}
print("Successfully liked post.")
post.hasLiked = !post.hasLiked
self.posts[indexPath.item] = post
self.collectionView.reloadItems(at: [indexPath])
}
}
// Handle if user likes or unlikes posts.
guard let uid = Auth.auth().currentUser?.uid else {return}
Database.database().reference().child("likes").child(key).child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
if let value = snapshot.value as? Int, value == 1 {
post.hasLiked = true
} else {
post.hasLiked = false
}
self.posts.append(post)
self.posts.sort(by: { (p1, p2) -> Bool in
return p1.creationDate.compare(p2.creationDate) == .orderedDescending
})
self.collectionView.reloadData()
}, withCancel: { (error) in
print("Failed to fetch like info for post:", error)
})
})
}) { (error) in
print("Failed to fetch post:", error)
}
}
我厌倦了植入post.likes = value
,所以我可以获取每个赞的价值并进行展示,但是我不知道这是否有意义,而且它没有用。