C6Silver C6Silver - 14 days ago 8
Swift Question

Firebase Observer not Removed in Swift

Top of class:

let ref = FIRDatabase.database().reference()
var handler:FIRDatabaseHandle!


From view coming on screen:

self.handler = self.ref.child("Requests").observe(.value, with: {(snapshot) in


Finally:

override func viewDidDisappear(_ animated: Bool)
{
super.viewDidDisappear(animated)

self.ref.removeObserver(withHandle: self.handler)
self.ref.removeAllObservers()
}


Unfortunately when the database is changed in another view the observer in the VC above is still called. I understand I should not need both removes but I am trying everything. From breakpoints I can see that the remove code is firing and I can also see that the observer is being called just once.

What am I missing in removing the observer?

Answer

You're removing the observer from the wrong reference.

let ref = FIRDatabase.database().reference().child("Requests")

Try making this your ref instead and then:

self.handler = self.ref.observe(...
Comments