我有firebase实时数据库。我有标签和用户。当有人点击按钮时我希望从标签获得价值,增加它并更新新值。但我有观察者,我不能用这段代码获得更新的价值:
DataService.dataService.TAG_REF.observe(.value, with: { (snapshot) in
self.tags = []
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let tag = Tag(key: key, dictionary: postDictionary)
self.tags.insert(tag, at: 0)
}
}
}
self.dashCollectionView.reloadData()
}) { (error) in
print(error.localizedDescription)
}
当我点击按钮时:
if sender.image(for: .normal) == UIImage(named: "like") {
DataService.dataService.TAG_REF.child(selectedTag.tagKey).observeSingleEvent(of: .value, with: { snapshot in
let totalLikeSnap = snapshot.value as! Dictionary<String, AnyObject>
var totalLike = totalLikeSnap["like"] as! Int
totalLike = totalLike + 1
DataService.dataService.TAG_REF.child(selectedTag.tagKey).child("like").setValue(totalLike)
})
let likedTags = DataService.dataService.CURRENT_USER_REF.child("likedTags").child(selectedTag.tagKey)
likedTags.setValue(["time": "getcurrenttimelater"])
sender.setImage(UIImage(named: "liked"), for: .normal)
sender.setTitle(String(selectedTag.tagLikes), for: .normal)
self.dashCollectionView.reloadData()
} else {
print("already liked")
}
但它并没有增加。如果有人帮我更新数据,我会很高兴。
tags {
-bB1231e23a24 {
comment: 0
image: "1"
like: 1
}
}
答案 0 :(得分:2)
首先,改变你在数据库中增加喜欢的方式。
func updateTotalNoOfPost(completionBlock : (() -> Void)){
let prntRef = FIRDatabase.database().reference().child("tags/\(selectedTag.tagKey)")
prntRef.child("like").runTransactionBlock({ (noOfLikes) -> FIRTransactionResult in
if let totalLikes = noOfLikes.value as? Int{
noOfLikes.value = totalLikes + 1
return FIRTransactionResult.successWithValue(noOfLikes)
}else{
return FIRTransactionResult.successWithValue(noOfLikes)
}
}, andCompletionBlock: {(error,completion,snap) in
print(error?.localizedDescription)
print(completion)
print(snap)
if !completion {
print("The value wasn't able to Update")
}else{
completionBlock()
}
})
}
必须有一个数组,您必须在其中保存您的collectionView数据源的noOfLike。更新数据库时,还要更新collectionView数据源。
当您的用户点击按钮时,在按钮功能中: -
updateTotalNoOfLikes{
print("Value incremented!")
// Here add the value to your collectionView datasource
//And then call collectionView.reloadData()
}