Trying to dig into Firebase child data can sometimes be confusing at the start.
Our philosophy is to keep data as Firebase Data as long as possible. That means instead of casting to dictionaries, let the data exist as DataSnapshots. And well, DataSnapshots are just cool; they are great containers that are very flexible and super easy to work with.
Additionally casting the child snapshots of a DataSnapshot to an array persists the order - great for iterating over those children.
Here's one possible solution to read the data in your question. There's no error checking and we're force unwrapping some optionals so that should be changed in your own code.
I've added comments along the way
func readCatAndChildren() {
let catRef = self.ref.child("categories") //self.ref points to our firebase
catRef.observeSingleEvent(of: .value, with: { snapshot in
//first get all of the top level categories which have uid's as their keys
let allUidSnaps = snapshot.children.allObjects as! [DataSnapshot] //put into an array, preserves order
//now iterate over each child
for uidSnap in allUidSnaps {
let uid = uidSnap.key //get the uid for each child
print("uid: (uid)") //print it to console
//each top level node has an items child which is a snapshot
// get the children of items and put them
// into an array - preserves order
let itemsSnap = uidSnap.childSnapshot(forPath: "items")
let allItemsSnap = itemsSnap.children.allObjects as! [DataSnapshot]
//iterate over each item child node, which is category id
for itemSnap in allItemsSnap {
let itemCatKey = itemSnap.key //get the child category id
// finally, get the child category name from the child category
let itemCatName = itemSnap.childSnapshot(forPath: "cat_name").value as? String ?? "No Item Cat Name"
print(" itemCatKey: (itemCatKey) catName: (itemCatName)") //print it out
}
}
})
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…