2

I am trying to check to see if a key/value (TestKey/TestValue) exists at a node and if it does do A and if it does not do B.

I have found this similar thread regarding this on StackOverflow but none of the solutions seemed to work for me: Checking if Firebase snapshot is equal to nil in Swift

I have a database set up that already has the TestKey/TestValue key pair inserted. Here is my code:

var ref: FIRDatabaseReference!
    ref = FIRDatabase.database().reference()

    ref.observeSingleEventOfType(.Value, withBlock: { (snapshot) in

      //A print test to see stored value before control flow
      print(snapshot.value!["TestKey"]) //returns TestValue
      print(snapshot.value!["NilKey"]) //returns nil

      // I change the value from TestKey <-> NilKey here to test the control flow
      if snapshot.value!["TestKey"] != nil {
            print("Exists currently")
        } else  {
            print("Does not exist currently")
        }

    }) { (error) in
        print(error.localizedDescription)
    }

The problem is that only "A" is executed, even if the print test shows that the result is nil.

I have tried to reverse the operations with == nil and also have tried "is NSNull".

I cannot seem to get the control flow to work properly. Maybe one of the following is the culprit but I am unsure:

  1. interaction of persistence with observesSingleEventOfType
  2. not removing the observer (do I even need to for observeSingleEventType?)
  3. something to do with optionals
  4. something to do with asynchronous calls
  5. something to do with the fact that firebase stores NSAnyObjects

Ultimately the goal is to check if a key/value pair exists and if it does exist: do nothing but if it does not exist: create it. What am I doing wrong and how can I get this control flow to work?

Community
  • 1
  • 1
Abhi
  • 270
  • 3
  • 12

1 Answers1

3

Ok so after much fiddling I found a solution that works, it was indeed posted as this answer (https://stackoverflow.com/a/35682760/6515861) from the earlier existing question I linked (Checking if Firebase snapshot is equal to nil in Swift).

The way to make it work is to input the TestKey in the reference itself, remove the reference from snapshot.value("TestKey"), and then use "is Null".

Here is the working code:

// Database already exists with "TestKey"/"TestValue"

var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()

    // replace "TestKey" with another string to test for nil
    ref.child("TestKey").observeSingleEventOfType(.Value, withBlock: { (snapshot) in 

    if snapshot.value is NSNull {
        print("Does not exist currently")
    } else {
        print("Exists currently")
    }


    }) { (error) in
        print(error.localizedDescription)
    }

I am happy I found this solution but if anyone wants to still answer the original question I would love to know why it does not work the other ways.

Community
  • 1
  • 1
Abhi
  • 270
  • 3
  • 12