Wilson Wilson - 9 days ago 6
Swift Question

Firebase, how do I return a handle so that I can call removeObserver?

Here's my observe event code:

let databaseRef = FIRDatabase.database().reference()
let query = databaseRef.child("palettes").queryOrdered(byChild: UserDefaults.standard.string(forKey: "UserTypeState")!).queryEqual(toValue: modifiedColor.hexValue())
// Change the value to the value of the color.

query.observe(.childAdded, with: { (snapshot) in
let URL = snapshot.childSnapshot(forPath: "URL").value as! String
self.URLArrayString.append(URL)

self.collectionView?.reloadData() //Reloads data after the number and all the URLs are fetched
self.noResultsLabel.isHidden = true
})


How do I retrieve the handle when that particular observer is called so that I can remove it when viewDidDissapear?

Answer

When you call observe it returns a handle to the registered observer.

You pass this handle to removeObserverWithHandle() to remove the observer.

let handle = query.observe(.childAdded, with: { (snapshot) in
    ....
})

And then:

query.removeObserverWithHandle(handle)