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:
- interaction of persistence with observesSingleEventOfType
- not removing the observer (do I even need to for observeSingleEventType?)
- something to do with optionals
- something to do with asynchronous calls
- 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?