Sam Sam - 3 years ago 67
iOS Question

Firebase get child name by value and remove it

My JSON looks like this:

username1: "WWOdh96Yr3Qs4N3GWDVq3OlQFfB2"
username2: "RJ6PztTLmsg222oUygWHtWpVHdg1"

I would like to get "username1" by their key which is (auth.uid)! and if its found i want to delete it, So after delete it will be looks like this:

username2: "RJ6PztTLmsg222oUygWHtWpVHdg1"


self.ref.child("users").queryOrderedByValue().queryEqual(toValue: user?.uid).observe(.value, with: { snapshot in

if snapshot.exists() {

snapshot.ref.child(snapshot.value as! String).removeValue() // this deleting every thing which is WRONG!

} else{

print("Not found--")


This code deleting everything in users. I just want to delete specific user.

Answer Source

First of all, my approach is if I want to query 1 value at 1 moment, like you are doing, I do a observeSingleEvent (is this the best approach?). But to solve your problem, you forgot to add your "users" path. Below code is more safe to use, since you force unwrap (which is not recommend for this case):

let dataRef = self.ref.child("users")
       if let usersUID = Auth.auth().currentUser?.uid{
    dataRef.child("users").queryOrderedByValue().queryEqual(toValue: usersUID).observeSingleEvent(.value, with: { snapshot in
       let values = snapshot.value as? NSDictionary
       for (key, value) in values{
       print(value) // does this print the uid?
       print(key) // or this one?

            self.ref.child("users/\(key)").removeValueWithCompletionBlock({ (err, ref) in
                if err != nil {
                } else {

Try to add this, right after the print(snapshot)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download