Ahmet Özrahat
Ahmet Özrahat

Reputation: 335

Swift Get Specific Value From Firebase Database

I'm trying to get a specific value from Firebase Database. I looked some of the documents such as Google's, but I couldn't do it. Here is the JSON file of the database:

{
    "Kullanıcı" : {
        "ahmetozrahat25" : {
            "E-Mail" : "[email protected]",
            "Yetki" : "user"
        },
        "banuozrht" : {
            "E-Mail" : "[email protected]",
            "Yetki" : "user"
        }
    }
}

Swift Code:

ref?.child("Kullanıcı").child(userName.text!).observeSingleEvent(of: .value, with: { (snapshot) in

    if let item = snapshot.value as? String{
        self.changedName = item
    }
})

I want to get E-Mail value of a user, not everybody's. How can I do that?

Upvotes: 11

Views: 15813

Answers (3)

Ahmet Özrahat
Ahmet Özrahat

Reputation: 335

At last I found a solution. If I declare a var and try to use later it returns nil, but if I try use snapshot.value as? String it's ok. Here is a example I did.

    ref: FIRDatabaseReference?
    handle: FIRDatabaseHandle?

    let user = FIRAuth.auth()?.currentUser

    ref = FIRDatabase.database().reference()

    handle = ref?.child("Kullanıcı").child((user?.uid)!).child("Yetki").observe(.value, with: { (snapshot) in

        if let value = snapshot.value as? String{

            if snapshot.value as? String == "admin"{
                self.items.append("Soru Gönder")
                self.self.tblView.reloadData()
            }
        }
    })

Upvotes: 10

Jay
Jay

Reputation: 35667

In your code, the snapshot will contain a dictionary of child values. To access them, cast the snapshot.value as a Dictionary and then accessing the individual children is a snap (shot, lol)

ref?.child("Kullanıcı").child(userName.text!)
                       .observeSingleEvent(of: .value, with: { (snapshot) in

    let userDict = snapshot.value as! [String: Any]

    let email = userDict["E-Mail"] as! String
    let yetki = userDict["Yetki"] as! String
    print("email: \(email)  yetki: \(yetki)")
})

Upvotes: 4

Rajesh73
Rajesh73

Reputation: 342

Add the "E-Mail" child to the query.

ref?.child("Kullanıcı").child(userName.text!).child("E-Mail").observeSingleEvent(of: .value, with: { (snapshot) in

    if let item = snapshot.value as? String{
        self.changedName = item
    }
})

Upvotes: 2

Related Questions