I'm using Firebase and try to implement Like Button such as Facebook or Instagram.
I have written some code , but I have noticed that the number of likes sometimes increase by more than one like when user taps the like button many times, very fast.
Code...
func handleLike(likeButton: UIButton, numberLabel: UILabel) { guard let uid = FIRAuth.auth()?.currentUser?.uid else { return } if let photoId = photo?.id { let ref = FIRDatabase.database().reference() let photoRef = ref.child("users").child(uid).child("likes").child(photoId) photoRef.observeSingleEventOfType(.Value, withBlock: { (snapshot) in if snapshot.value is NSNull { likeButton.setImage(UIImage(named: "LikeFilled"), forState: .Normal) likeButton.setTitleColor(UIColor.redColor(), forState: .Normal) ref.child("users").child(uid).child("likes").child(photoId).setValue(true) ref.child("photos").child(photoId).child("likes").child(uid).setValue(true) self.photo?.adjustLikes(true) if let numberofLikes = self.photo?.numberofLikes { ref.child("photos").child(photoId).child("numberofLikes").setValue(numberofLikes) numberLabel.text = String(numberofLikes) + "Likes" } } else { likeButton.setImage(UIImage(named: "UNLike"), forState: .Normal) likeButton.setTitleColor(UIColor(r:143, g: 150, b: 163), forState: .Normal) ref.child("users").child(uid).child("likes").child(photoId).removeValue() ref.child("photos").child(photoId).child("likes").child(uid).removeValue() self.photo?.adjustLikes(false) ref.child("photos").child(photoId).child("numberofLikes").setValue(self.photo?.numberofLikes) if let numberofLikes = self.photo?.numberofLikes { ref.child("photos").child(photoId).child("numberofLikes").setValue(numberofLikes) numberLabel.text = String(numberofLikes) + "Likes" } } }, withCancelBlock: nil) } } class Photo: NSObject { func adjustLikes(addLike: Bool) { if addLike { numberofLikes = numberofLikes! + 1 } else { numberofLikes = numberofLikes! - 1 } } } How can I implement synchronous function such as LIKE/UNLIKE function ? I thought that I could use with CompletionBlock, but I couldn't implement it with .observeSingleEventOfType...
I appreciate any help...