gpt4 book ai didi

ios - swift Firebase 删除观察者

转载 作者:行者123 更新时间:2023-11-28 15:29:43 26 4
gpt4 key购买 nike

我注意到喜欢或不喜欢的打印被触发的次数与我打开 View Controller 的次数一样多,所以我在 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)
}

最佳答案

请引用此链接:-

https://firebase.google.com/docs/database/ios/read-and-write#detach_listeners

此外,在通过处理程序删除所有引用后,只需 removeAllObservers 以防任何观察者离开并且它可能会继续同步,并且应该在收到来自 firebase 的快照后主要将其删除,因为我也面临同样的问题解决了我的问题。

关于ios - swift Firebase 删除观察者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44861473/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com