我注意到,当我打开视图控制器时,喜欢或不喜欢的打印被触发了很多次,所以我在viewDidDisappear中添加了一个删除观察者(我尝试了所有列出的内容),但它继续多次触发,有人可以帮我吗?
这是我的代码:
private var databaseHandle: FIRDatabaseHandle!
var ref = FIRDatabase.database().reference()
var isLiked: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
isLiked = false
databaseHandle = ref.child("favperuser").child(FIRAuth.auth()!.currentUser!.uid).observe( .value, with:{(snap) in
if snap.hasChild(self.detailId){
print("is liked")
self.isLiked = true
self.likeButton.setTitle("Unlike", for: .normal)
self.likeButton.setImage(UIImage(named: "star-")?.withRenderingMode(.alwaysOriginal), for: .normal)
self.likeButton.setImage(UIImage(named: "star-")?.withRenderingMode(.alwaysOriginal), for: .highlighted)
}else{
print("not liked")
self.isLiked = false
self.likeButton.setTitle("Like!", for: .normal)
self.likeButton.setImage(UIImage(named: "star+")?.withRenderingMode(.alwaysOriginal), for: .normal)
self.likeButton.setImage(UIImage(named: "star+")?.withRenderingMode(.alwaysOriginal), for: .highlighted)
}
})
self.isLiked = false
}
@IBAction func likePressed(_ sender: UIButton) {
if self.isLiked == false {
ref.child("favperuser").child( FIRAuth.auth()!.currentUser!.uid).updateChildValues([detailId: true])
} else {
ref.child("favperuser").child( FIRAuth.auth()!.currentUser!.uid).child(detailShellId).removeValue { (error, ref) in
if error != nil {
print("error \(error)")
}
}
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
ref.removeObserver(withHandle: databaseHandle)
ref.child("favperuser").removeObserver(withHandle: databaseHandle)
ref.child("favperuser").child(FIRAuth.auth()!.currentUser!.uid).removeObserver(withHandle: databaseHandle)
}
答案 0 :(得分:1)
请参阅此链接: -
https://firebase.google.com/docs/database/ios/read-and-write#detach_listeners
在删除处理程序的所有引用之后,只有removeAllObservers用于该ref,以防任何观察者离开并且它可能继续同步,并且应该在从firebase接收到快照之后将其删除,因为我也面临同样的问题我的问题。