Firebase when query is empty

Question!

I perform a query using firebase to check if there are any objects that have a child with a certain value. The problem is if there are no such objects the code doesn't run. So in the code below if there are no objects that have a child with facebookID that is 17 the rest of the code will never run. Is there a way to determine when a query finds 0 results?

func previousUser(completion:(result:Bool)->Void){

    var queryFound = false
    print("check if user is previous")
    print(UserData.globalfacebookID)
    let ref = Firebase(url:"https://amber-torch-556.firebaseio.com/Users")
    ref.queryOrderedByChild("facebookID").queryEqualToValue(17).observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in

    print(snapshot.childrenCount)
    print("query has ran")
    UserData.globalparseID = snapshot.key

    queryFound = true
    completion(result:queryFound)

})


Answers

To check whether a query returns 0 results, you can check the snapshot as following:

if snapshot.exists() {
   // write relevant logic here
}
else {
   // handle the case when a query finds 0 results 
}

In your case,

func previousUser(completion:(result:Bool)-


Check your ref to make sure it's valid.

and try this

        ref.queryOrderedByChild("facebookID").queryEqualToValue(17)
           .observeEventType(.Value, withBlock: { snapshot in

              if snapshot.value is NSNull {
                 print("dude, snapshot was null")
              } else {
                 print(snapshot.key)
              }

        })

Change .ChildAdded to .Value and then check for NSNull

By : Jay


This video can help you solving your question :)
By: admin