Ian Ian - 1 month ago 27
iOS Question

how do I set a variable to get value from Firebase database structure in Swift

I am now struggling with Firebase database.

For example here's my database structure

"Menus" : {
"Day1" : {
"mealDes" : "delicious Thai food",
"date" : "2016.10.20",
"mealname" : "kakoon"
},


and I need to set a variable to get the value of "date".

something like : print(theDateVar) //get 2016.10.20

I tried some observeSingleEvent and observe method, they're not working!

DataService.ds.REF_MENUS.observeSingleEvent(of: .value, with: { snapshot in

if let date = snapshot.childSnapshot(forPath: "menuDate") as? String {

print ("date is \(date)")

}

})


I know retrieving data from database is frequently asked,
but all the question i searched is not helping

please help me out :(, I spend half of my weekend on this but still...

UPDATE

Hi, it totally worked!

my code now is looks like the following :

FIRDatabase.database().reference().child("Menus/Day1").observeSingleEvent(of: .value, with: {(snap) in

if let snapDict = snap.value as? Dictionary <String, AnyObject>{

let date = snapDict["mealPic"] as! String


let OrderInfo = DataService.ds.REF_ORDER
let USERUID = FIRAuth.auth()!.currentUser!.uid
let userinfo = OrderInfo.child("date").child(USERUID).child("data")

userinfo.child("address").setValue("SomeRandomAddress")
userinfo.child("phonenumber").setValue("666888")
}
})


but what if I want to set the address value and the phone number value as the value i have in other node (user)

"Menus": {
"User" : {
"WbxT2bBgcnYOEn2YUqpvh4mtxvo2" : {
"address" : "taipei City ",
"phonenumber" : "0933555666",
"provider" : "Firebase"
}


do i use observeSingleEvent again in observeSingleEvent ?

Answer

Try using :-

 FIRDatabase.database().reference().child("menus/Day1").observeSingleEvent(of: .value, with: {(snap) in

        print(snap)

        if let snapDict = snap.value as? [String:AnyObject]{

            let date = snapDict["date"] as! String
            print(date)

        }
    })
Comments