Abdulmoiz Ahmer
Abdulmoiz Ahmer

Reputation: 2341

How to know which subchild is updated in childChanged eventtype of realtime firebase in swift 4

Assuming My Firebase RealTime Database has the child name Users which further has sub-child which are emails like this "[email protected]", the sub-child emails further have sub-child called name, age, and country.

I added an observeEvent on child changed the snippets looks like this.

 ref.child("USERS").child("christianLiz@gmail,com").observe(.childChanged, with: { snapshot in

        if snapshot.exists(){
            let value = snapshot.value as? NSDictionary
            if value!["name"] != nil{
                print("here")
            }else{
                print("not here")
            }

    }){ (error) in
        print("")
    }

When i test after changing the value of country the app crashes and cause is this value!["name"]. Now i do know that the childChanged event is only returning the child which is changed in my testing scenario "country" so other values are notin snapshot but i want to check which one is updated name or age or country. How can i modify the code above to achieve this.

Upvotes: 1

Views: 177

Answers (1)

wasif
wasif

Reputation: 327

Use hasChild to check if a child exists or not:

if snapshot.hasChild("country"){
      print("found")
    } else {
      print("not found")
}

Upvotes: 1

Related Questions