Get The Data from All Children in Firebase Using Swift

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

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)
}

}
})
}

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)
}
}
}
}

How to read all child data from firebase

The key to firebase is to keep data in snapshots as long as you can. So in this case instead of casting items to dictionaries, which loose ordering or arrays that get more complex as the structure gets deeper, leverage DataSnapshots.

Here's the main function to read all shops in ShoppingMall1 - similar to the code in your question.

func readMallShops() {
let ref = self.ref.child("ShoppingMallList").child("ShoppingMall1")
ref.observeSingleEvent(of: .value, with: { snapshot in
let allShopsSnap = snapshot.children.allObjects as! [DataSnapshot]

for shopSnap in allShopsSnap {
let shop = ShopClass(withSnap: shopSnap)
}
})
}

Then a class that holds data about each shop. Note that I pass each snapshot in to initialize the class

class ShopClass {
var name = ""
var height = ""

convenience init(withSnap: DataSnapshot) {
self.init()
let name = withSnap.childSnapshot(forPath: "ShopName").value as? String ?? "No Shop Name"
print("Shop: \(name)")
self.name = name
let shopPathSnap = withSnap.childSnapshot(forPath: "ShopPath")
let shopChildSnap = shopPathSnap.children.allObjects as! [DataSnapshot]
for childDataSnap in shopChildSnap { //iterate over the array in ShopPath
let height = childDataSnap.childSnapshot(forPath: "Height").value as! String
print(" height: \(height)")
self.height = height
}
}
}

And the output looks like this

Shop name: Test
height: 1,180
Shop name: Test 2
height: 2,000

I left off the other child nodes as if you can read height, you can read the rest. So this just assigns and prints out the shop name and height (as a string).

A suggestion as well. Arrays are not well suited for NoSql databases and their use is very situational (avoid if possible). If you're using an array, there's probably a better structure available.

How to retrieve child data from firebase realtime database on Swift 5

Assuming you have multiple posts like this

posts
0
tags
0: 100
1: 200
1
tags
0: 100
1: 200

Here's the code that will iterate over each post, one at a time, read the content and then read the tags and output them to the console.

func readPostTags() {
let postsRef = self.ref.child("posts")
postsRef.observe(.childAdded, with: { snapshot in
let content = snapshot.childSnapshot(forPath: "creation_date").value as! String
let tagsSnap = snapshot.childSnapshot(forPath: "tags")
let allChildTagsSnap = tagsSnap.children.allObjects as! [DataSnapshot]
for tagChildSnap in allChildTagsSnap {
let key = tagChildSnap.key
let value = tagChildSnap.value as! Int
print(content, key, value)
}
})
}

and the output

0 100
1 200
0 100
1 200

Keep in mind that .childAdded will leave an observer on that node and notify you of further additions.

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