How to get values inside nested keys in Firebase on Swift

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


How to get values inside nested keys in Firebase on Swift



I'm trying to get values inside two nested keys in Firebase.



This is my database structure:



I need to put all the value of name inside an array. Here is my code where I'm accessing just the node "user". I was thinking that I could use "queryOrderedByKey" one after another, but in that case xCode crashes and says something like multiple quires aren't allowed.


Database.database().reference().child("user").queryOrderedByKey().observe(.childAdded) { (snapshot) in

if snapshot.value != nil {

let result = snapshot.value as! [String : AnyObject]

if let name = result["name"] as? String {
self.myArray.append(name)
}

DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})

}
}



And this is what I'm getting when printing the result.
Result




2 Answers
2



Here is the answer


Database.database().reference().child("user").observe(.childAdded) { (snapshot) in

if let dictinoary = snapshot.value as? [String: Any] {
if let myFinalStep = dictinoary["GeneralInformation"] as? [String: Any] {
print(myFinalStep["name"])

}
}
}



Tigran's answer is very good but here's an alternative. This code iterates over each child node within 'user' node and looks into a deep path to get the name. Note this leaves a childAdded observer to the user node so if any additional nodes are added, this will fire again.


let usersRef = self.ref.child("user")
usersRef.observe(.childAdded, with: { snapshot in
if let name = snapshot.childSnapshot(forPath: "GeneralInformation")
.childSnapshot(forPath: "name").value as? String {
print(name)
}
})



If you want to read the names in once and not leave an observer, here's an alternative


let usersRef = self.ref.child("user")
usersRef.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let snap = child as! DataSnapshot
if let name = snap.childSnapshot(forPath: "GeneralInformation")
.childSnapshot(forPath: "name").value as? String {
print(name)
}
}
})






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Visual Studio Code: How to configure includePath for better IntelliSense results

Spring cloud config client Could not locate PropertySource

Regex - How to capture all iterations of a repeating pattern?