Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 992
Ahmet Özrahat Avatar asked Feb 15 '17 17:02

Ahmet Özrahat


2 Answers

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()
            }
        }
    })
like image 119
Ahmet Özrahat Avatar answered Oct 22 '22 17:10

Ahmet Özrahat


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)")
})
like image 42
Jay Avatar answered Oct 22 '22 17:10

Jay