我一直在尝试实现一个用户可以喜欢帖子的集合视图,但出于某种原因,当用户这样做时,它更新了feed,但只是将单元格的数量加倍并留下应该消失的旧单元格。简而言之,一半的细胞被更新,另一半是旧的值。基本上我无法弄清楚如何简单地更新当前单元格而没有问题。理想情况下,我希望用户按下“喜欢”按钮,除了那个按钮转到“不同”以及要在收集视图中更改帖子上的喜欢数量之外别无其他任何事情。
以下是加载集合视图单元格的代码:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = feedCollectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! MyGroupFeedCollectionViewCell
cell.postKey = feedArray[indexPath.row].postKey
//clears the cells first
cell.profileImage.image = nil
cell.usernameLabel.text = nil
cell.usernameLabel2.text = nil
cell.groupName.text = nil
cell.postImageView.image = nil
cell.postCaptionTextView.text = nil
cell.timeStamp.text = nil
//load profile picture
cell.profileImage.sd_setImage(with: URL(string: feedArray[indexPath.row].ProfilePic), placeholderImage: UIImage(named:"no profile picture.png"))
//load username
cell.usernameLabel.text = feedArray[indexPath.row].Username
cell.usernameLabel2.text = feedArray[indexPath.row].Username
//load groupName when in home feed
cell.groupName.text = feedArray[indexPath.row].GroupName
//load postImage
cell.postImageView.sd_setImage(with: URL(string: feedArray[indexPath.row].PostImage), placeholderImage: UIImage(named:"penguinPanorama"))
//load caption
cell.postCaptionTextView.text = feedArray[indexPath.row].caption
//load likes once likes are implemented
//checks if the user has liked the post or not
databaseRef.child("likes").child((FIRAuth.auth()?.currentUser?.uid)!).child(feedArray[indexPath.row].postKey).observe(.value, with: { (snapshot) in
if(snapshot.exists())
{
cell.liked = "Yes"
cell.likeButton.setTitle("Unlike", for: .normal)
}
else{
cell.liked = "No"
cell.likeButton.setTitle("Like", for: .normal)
}
})
以下是按下之类按钮的功能代码:
@IBAction func likeButton_tapped(_ sender: Any) {
self.likeButton.isEnabled = false
print(self.postKey)
print(self.liked)
//make it so liking or unliking adds or subtracts from the total number of likes on the post
if liked == "Yes"
{
self.databaseRef.child("likes").child((FIRAuth.auth()?.currentUser?.uid)!).child(self.postKey).removeValue()
let NewLikeNumber = likeNumber - 1
self.databaseRef.child("GroupPosts").child(self.groupName.text!).child(self.postKey).child("likes").setValue(NewLikeNumber)
print(NewLikeNumber)
}
else{
self.databaseRef.child("likes").child((FIRAuth.auth()?.currentUser?.uid)!).child(self.postKey).setValue("")
let NewLikeNumber = likeNumber + 1
self.databaseRef.child("GroupPosts").child(self.groupName.text!).child(self.postKey).child("likes").setValue(NewLikeNumber)
print(NewLikeNumber)
}
self.likeButton.isEnabled = true
}
答案 0 :(得分:0)
对于喜欢的人,我建议你使用Firebase交易,因为同时修改你的计数可能会变得一团糟:
func likePost(_ post: Post, completion: @escaping () -> ()) {
guard let currentUserId = Auth.auth().currentUser?.uid else {
return
}
databaseRef.child(likes).child(currentUserId).child(postKey).runTransactionBlock ( { (currentData: MutableData) -> TransactionResult in
if var data = currentData.value as? [String: Any] {
var count = data["likesCount"] as! Int
count += 1
data["likesCount"] = count
currentData.value = data
return TransactionResult.success(withValue: currentData)
}
return TransactionResult.success(withValue: currentData)
}, andCompletionBlock: { (error, success, snapshot) in
// ...
})
}
当然,对于不喜欢帖子的用户来说同样如此。
现在要知道用户是否喜欢这个帖子,你可以在你的类中创建一个布尔值来在本地保存类似的状态:
private var isPostLiked = false
每当用户点击“赞”按钮时,请执行以下简单检查:
func handleLikeTapped() {
guard let post = post else {
return
}
if isPostLiked {
NetworkManager.shared.likePost(post, completion: { [weak self] in
// Once the completion handler of your method is called, the likes count in your database is now updated.
// To avoid making another read in the database just now, you can just
// Update your count (a label that shows how many likes a specific post received I guess ?) locally here so that the user can see in realtime the change (with animation or not depending on what you want to achieve)
// And finally update the like state of the post so that if the user click again on like it wouldn't mess everything up:
self?.isPostLiked = false
})
}
else {
NetworkManager.shared.dislikePost(post, completion: { [weak self] in
// ...
})
}
}
现在当然,如果你需要访问不同视图控制器中的like count,你只需使用observeSingleEvent(of: .value)
从数据库中获取更新的likesCount。
如果您有任何疑问,请与我们联系!