我正在使用subprocess.check_call(command.split(" "),shell=True)
并尝试实施Firebase
,例如Facebook或Instagram。
我已经编写了一些代码,但是我注意到,当用户多次点击类似按钮时,喜欢的次数有时会增加不止一次,非常快。
...代码
Like Button
如何实现LIKE / UNLIKE功能等同步功能?
我认为我可以使用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
}
}
}
,但我无法用with CompletionBlock
实现它...
我感谢任何帮助...
答案 0 :(得分:1)
我一直在努力实现像计数器一样但是使用解析作为baas。我采用的最佳解决方案是不直接更新服务器上的计数器值,但是在具有上一个状态(喜欢与否)的服务器上超时完成更新时设置超时:
检查是否喜欢并反转类似状态:liked = !liked
相应地更新本地计数器:liked ? likeCounter++ : likeCounter--
likeLabel.text = "\(likeCounter)"
最后检查是否有一个定时器设置为更新服务器状态:
if(likeTimer != nil) {
// Stop current operation
likeTimer.invalidate()
}
//Setup a set time out 1s func
likeTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(updateLikeCounter), userInfo: nil, repeats: false)
func updateLikeCounter(){
//if liked == true and the like operation is not submitted to server ==> increment like counter on server . else do nothing
//if like == false and a like operation have been submitted to server (user is in the list of users who like the image) ==> decrement like counter on server . else do nothing
}
我希望这可以帮到你