Reputation: 2079
I am trying to access the contents of data that is stored via childByAutoID in firebase using swift. Currently I am very new to this and am just printing out the value of snapshot.value. I want to be able to access both key value pairs stored in each ID.
Here is my current code:
override func viewDidLoad() {
super.viewDidLoad()
let ref = FIRDatabase.database().reference()
ref.child("Phrases").observeSingleEvent(of: .value, with: {
snapshot in
let value = snapshot.value as? NSDictionary
print(value)
})
}
This is outputting:
Optional({
"-KkNM7b33sqba0XF-Nob" = {
phrase = "Bonjour!";
translation = "Hello!";
};
})
I am want to be able to access value["phrase"] and translation as well.
How do I do this?
EDIT: Here is a photo of the db:
Upvotes: 1
Views: 614
Reputation: 8020
The way I usually do this is by:
ref.child("Phrases").observeSingleEvent(of: .value, with: { snapshot in
let value = snapshot.value as! [String:Any]
let name = value["phrase"] as? String ?? ""
})
Alternatively you could unwrap it first
ref.child("Phrases").observeSingleEvent(of: .value, with: { snapshot in
if let value = snapshot.value as? [String:Any] {
let name = value["phrase"] as? String ?? ""
}
})
Upvotes: 2