Daniel Daniel - 6 months ago 44
Swift Question

Firebase queries not calling block when there are no results

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

Jay Jay
Answer

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.