Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 952
Daniel Avatar asked Mar 13 '23 17:03

Daniel


1 Answers

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")
        }
    })
like image 191
Jay Avatar answered Apr 26 '23 05:04

Jay