Lance Samaria
Lance Samaria

Reputation: 19592

What to do when snapshot.exists() returns false?

I have a ref that exists and I use observeEventType to query the data. But the ref might not have data in it due to the user deleting it. I test it using snapshot.exists(). In the situation below snapshot.exists() will return false/no. Since it's false I want to do something else but the code never runs

How do I so something else when snapshot.exists() returns false/no?

     //there is no data at levelTwo so there's nothing to observe
let levelTwoRef = dbRef.child("players").child("uid").child("levelTwo")

levelTwoRef.observeEventType(.ChildAdded, withBlock: {
        (snapshot) in
        if snapshot.exists(){
           if let dict = snapshot.value as? [String:AnyObject]{
              let power = dict["power"] as? String
              let score = dict["score"] as? String
           }
        //this will never run because the data has been deleted
        } else{
          do something else as an alternative //why isn't this running??
        }
    })

enter image description here

Upvotes: 3

Views: 3008

Answers (2)

Lance Samaria
Lance Samaria

Reputation: 19592

Firebase has a .hasChild function that you can run on a child to see if it exists:

func hasChild(_ childPathString: String) -> Bool

It takes a child as a String argument and returns True or False depending on wether it exists or not.

The way to check if a child exists is to first set a path to the child before the child your looking for. In the situation from the question the child to look for is "levelTwo" and the child before that is uid:

 //there is no data at levelTwo so there's nothing to observe
let levelTwoRef = dbRef.child("players").child("uid").child("levelTwo")

Assuming you know the uid ref definitely exists set a constant for the uid ref instead of the levelTwo ref

// uid path definitely exists
let uidRef = dbRef.child("players").child("uid")

Run .value on the uid ref and inside the callback check to see if the levelTwo ref exists:

uidRef?.observeSingleEvent(of: .value, with: {
                (snapshot) in

                if snapshot.hasChild("levelTwo"){
                     // true -levelTwo ref Does exist so do something
                }else{
                    // false -levelTwo ref DOESN'T exist so do something else
                }
}

Upvotes: 1

Pat Needham
Pat Needham

Reputation: 5928

You are running that inside observeEventType with the type .ChildAdded, which would return the snapshot of each new path that is created. If you just need to retrieve the value once you should use observeSingleEventOfType (link), with .Value as the event type.

Upvotes: 0

Related Questions