I'm using Firebase and I want to query to see if something exists. It gets called when a value is found, but the block does not get called when nothing is found. Is this expected behaviour?
ref.queryOrderedByKey().queryEqualToValue(channelName).observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in
print("found channel: \(snapshot.key)")
}, withCancelBlock: { error in
print(error.description)
})
Have I done something wrong? Thanks
To check for no data (snapshot == NULL) it's done this way
let refToCheck = myRootRef.childByAppendingPath(channelNameString)
refToCheck.observeEventType(.Value, withBlock: { snapshot in
if snapshot.value is NSNull {
print("snapshot was NULL")
} else {
print(snapshot)
}
})
Queries are pretty heavy by comparison to the .observeEventType and since you already know the specific path you are checking for it will perform much better.
Edit: You can also use
if snapshot.exists() { ... }
Firebase queries are best used when you want to retrieve child nodes that contain specific values or a range of values.
Edit for Firebase 3.x and Swift 3.x
let refToCheck = myRootRef.child(channelNameString)
refToCheck.observe(.value, with: { snapshot in
if snapshot.exists() {
print("found the node")
} else {
print("node doesn't exist")
}
})
Note 1) the logic was changed a bit as we now leverage .exists to test for existence of a snapshot. Note 2) this code leaves an observer active in Firebase so if the node is created at a later time, it will fire.
If you want to check for a node and don't want to leave an observer watching for that node do this:
let refToCheck = myRootRef.child(channelNameString)
refToCheck.observeSingleEvent(of: .value, with: { snapshot in
if snapshot.exists() {
print("found the node")
} else {
print("node doesn't exist")
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With