您好我有一个使用firebase的取消关注/关注系统,但它非常迟钝。如果我按下按钮100次,有时会从跟随切换到取消关注。数据有效,但它很混乱,因为当我关注用户并想要取消关注时,它会显示如下,但我需要文本说取消关注以删除值。顶部代码是检查当前用户是否跟随并设置按钮文本,第二个代码是设置数据的代码。
修改
我检查了我的数据库,发生的事情是它正在创建另一个重复值并同时删除它....任何想法如何解决这个问题?
Database.database().reference().child("Businesses").child(self.loggedInUser!.uid).child("following").queryOrderedByKey().observe(.value, with: { (snapshot) in
if let following = snapshot.value as? [String : AnyObject] {
for (_, value) in following {
if value as! String == self.otherUser?["uid"] as! String {
self.follow.setTitle("Unfollow", for: .normal)
print("You are following the user")
} else {
self.follow.setTitle("Follow", for: .normal)
print("You are not following the user")
}
}
}
})
@IBAction func followButton(_ sender: Any) {
let userID = Auth.auth().currentUser!.uid
let ref = Database.database().reference()
let key = ref.child("Businesses").childByAutoId().key
ref.child("Businesses").child(userID).child("following").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in
if let following = snapshot.value as? [String : AnyObject] {
for (item, value) in following {
if value as! String == self.otherUser?["uid"] as! String {
ref.child("Businesses").child(userID).child("following/\(item)").removeValue()
ref.child("Businesses").child(self.otherUser?["uid"] as! String).child("followers/\(item)").removeValue()
}
}
}
// Follow
if(self.follow.titleLabel?.text == "Follow") {
let following = ["following/\(key)" : self.otherUser?["uid"] as! String]
let followers = ["followers/\(key)" : userID]
ref.child("Businesses").child(userID).updateChildValues(following as Any as! [AnyHashable : Any])
ref.child("Businesses").child(self.otherUser?["uid"] as! String).updateChildValues(followers)
}
})
}