Get Children of Children in Firebase Using Swift

Get Children of Children in Firebase Using Swift

You can try

@IBAction func editAddressButtonPressed(_ sender: Any) {
self.ref?.child("Users").queryOrdered(byChild: "username").queryEqual(toValue: username.text!).observe(.value, with: { (snapShot) in
if !snapShot.exists() {
print("nothing found")
} else {
print("found it!")
print(snapShot)
let snapShotValue = snapShot.value as! [String:[String:Any]]
Array(snapShotValue.values).forEach {
let fName = $0["FirstName"] as! String
print(fName)
}

}
})
}

Get the data from all children in firebase using swift

You'll want to attach the observer one level higher in the JSON, and then loop over the child nodes:

ref.observeSingleEvent(of: .value) { snapshot in
for case let child as FIRDataSnapshot in snapshot.children {
guard let dict = child.value as? [String:Any] else {
print("Error")
return
}
let latitude = dict["Latitude"] as Any
let longtitude = dict["Longtitude"] as Any
print(longtitude)
print(latitude)
}
}

Loop syntax taken from Iterate over snapshot children in Firebase, but also see How do I loop all Firebase children at once in the same loop? and Looping in Firebase

Swift Firebase get values in children

Your ref variable points to the posts node:

let postsRef = ref.child("posts")

Then you retrieve the value of that node, and loop over its children:

postsRef.observeSingleEvent(of: .value) { (snapshot) in
if snapshot.exists() {
for child in snapshot.children {

That means that child is a snapshot of xPCdfc5d...Oms2. You then get a dictionary of the properties of this child snapshot and print the imageURL property in there:

            let snap = child as! DataSnapshot
let dict = snap.value as! [String: Any]
let myPostURL = dict["imageURL"] as! String
print("POST URL: " + myPostURL)

But if you follow along closely in your JSON, the xPCdfc5d...Oms2 node doesn't have a property imageURL.

You have two dynamic levels under posts, so you need two nested loops over the value:

postsRef.observeSingleEvent(of: .value) { (snapshot) in
if snapshot.exists() {
for userSnapshot in snapshot.children {
let userSnap = userSnapshot as! DataSnapshot
for childSnapshot in userSnap.children {
let childSnap = childSnapshot as! DataSnapshot

let dict = childSnap.value as! [String: Any]
let myPostURL = dict["imageURL"] as! String
print("POST URL: " + myPostURL)
}
}
}
}

Swift Firebase read children of a child

Try the following and let me know if it works now:

// SEARCHES FOR SHARING CODE IN DATABASE (ONLINE)
let parentRef = Database.database().reference().child("Recipes")

parentRef.observeSingleEvent(of: .value, with: { snapshot in

// SHOWING WHATEVER WAS RECEIVED FROM THE SERVER JUST AS A CONFIRMATION. FEEL FREE TO DELETE THIS LINE.
print(snapshot)

// PROCESSES VALUES RECEIVED FROM SERVER
if ( snapshot.value is NSNull ) {

// DATA WAS NOT FOUND
print("– – – Data was not found – – –")

} else {

// DATA WAS FOUND
for user_child in (snapshot.children) {

let user_snap = user_child as! DataSnapshot
let dict = user_snap.value as! [String: String?]

// DEFINE VARIABLES FOR LABELS
let recipeName = dict["Name"] as? String
let recipeDescription = dict["Description"] as? String
print("– – – Data for the recipe \(recipeName) with the description \(recipeDescription) was found successfully! – – –")
}
}
}

If you only want to retrieve the name and description for one specific recipe, you should change the third line to

parentRef.queryEqual(toValue:DefineWhatToSearchForHere).observeSingleEvent(of: .value, with: { snapshot in

If you constantly want to update to reflect changes, you can either call this function every x seconds using a timer and adding it to override func viewDidLoad() such as

time = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(ViewController.updateFBData), userInfo: nil, repeats: true)

after creating a function called func updateFBData() in which you do whatever you want to do to get new data (see above) and calling it in a defined timeInterval

or you can do what Attila Hegedüs in this excellent tutorial.

Get children of child nodes from firebase (swift 3)

try this:-

   func loadImages (){
Database.database().reference(withPath:
"Студии").child("Дубаи").observe(.value, with: { (snapShot) in
if snapShot.exists() {
let array:NSArray = snapShot.children.allObjects as NSArray

for child in array {
let snap = child as! DataSnapshot
if snap.value is NSDictionary {
let data:NSDictionary = snap.value as! NSDictionary
if let dict = data.value(forKey: "Images") {
let dictImage:NSDictionary = dict as!
NSDictionary
if let image = dictImage["image1"] {
print(image)
}
}
}

// newImage1.append(url2)

}
}
})
}

Iterate over children within a snapshot and get values within each child in Firebase

I assume you are reading the parent node with observeSingleEvent(of: .value so this function reads the data, maintains order, unwraps each child node safely and prints the time. I cast the value to an String but you could use double or something else. I suggest using a double to store your timestamps.

func readTimes() {
let ref = self.ref.child("00001")
ref.observeSingleEvent(of: .value, with: { snapshot in
let allChildren = snapshot.children.allObjects as! [DataSnapshot]
for snap in allChildren {
if let time = snap.childSnapshot(forPath: "timeDetected").value as? String {
print("timeDetected = \(time)")
}
}
})
}

and the output

timeDetected = 2018-05-28T16:00:13Z
timeDetected = 2018-05-28T16:00:18Z
timeDetected = 2018-05-28T16:00:43Z

Firebase - retrieve all child keys and child values into separate arrays in Swift

Snapshots have two properties.

snapshot.key
snapshot.value

When using an observer with .value. all of the key: value children are returned in the snapshot. They can be iterated over to capture each key: value pair like this.

ref.observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
let value = snap.value
print("key = \(key) value = \(value!)")
}
})

Keep in mind that the value property could be a string, number, array or another dictionary (snapshot). In the original question it's a String.



Related Topics



Leave a reply



Submit