Search code examples
swiftfirebasefirebase-realtime-databaseobservers

Firebase observer not working, why won't it keep a watch on the value change?


I am trying to set a Firebase observer by calling the following:

ref.child(id).child("isLocked").observe(.value, with: { snapshot in

    print("isLocked = ", snapshot.value!)

})

When the view loads it works perfectly. It prints out the correct value.

When I go change the value either in Firebase itself or on a separate device the isLocked is never printed again. When it should be since I have an observer on the path. What gives?

The end goal here is to have a UIButton available based on if the lock value is true of false.

The view is loaded with the button.isHidden = true.

UPDATE

I found the source of my issue with observer not "Working"

It would seem that there is a timing issue.

In the previous view controller (which segues into the new view controller) I am calling ref.child(pID).child("isLocked").removeAllObservers() in the 'viewDidDisappear' function

And in the new view controller I am 'trying' to setup the same path observer 'ref.child(id).child("isLocked").observe(.value, with: { snapshot in'

which I guess the removeAllObservers() trumps the setup of the new observer!? How do I get over this!?


Solution

  • I found the source of my issue with observer not "Working"

    It would seem that there is a timing issue.

    In the previous view controller (which segues into the new view controller) I am calling ref.child(pID).child("isLocked").removeAllObservers() in the viewDidDisappear function

    And in the new view controller I am 'trying' to setup the same 'path observer' ref.child(id).child("isLocked").observe(.value, with: { snapshot in.

    Which I guess the removeAllObservers() trumps the setup of the new observer!?

    To remedy this you need to setup specific handles per observer! Make sure to use unique var names and no reuse and then call the following instead of removeAllObservers():

    ref.child(id).child("isLocked").removeObserver(withHandle: confirmVCRefHandle!)
    

    the above handle name confirmVCRefHandle is unique and the timing issue is overcome!