I want to fill an array by fetching values from one firebase node and use those values to fetch information from a different firebase node. How do I do that?
This is what my firebase database looks like:
{
"MainTree" : {
"subTree1" : {
"JiRtkpIFLVFNgmNBpMj" : {
"PiRterKFLVFNgmFFFtu" : "PiRterKFLVFNgmFFFtu"
"TfRterKFLVFNgmFGFre" : "TfRterKFLVFNgmFGFre",
"X4RterKFLVFNgmaDFca" : "X4RterKFLVFNgmaDFca"
}
},
"subTree2" : {
"PiRterKFLVFNgmFFFtu" : {
"username" : "user1",
"uid" : "PiRterKFLVFNgmFFFtu"
},
"TfRterKFLVFNgmFGFre" : {
"username" : "user2",
"uid" : "TfRterKFLVFNgmFGFre"
},
"X4RterKFLVFNgmaDFca" : {
"username" : "user3",
"uid" : "X4RterKFLVFNgmaDFca"
}
}
}
}
My Function
func fetchAllInformation(uid: String, completion: @escaping ([UserData]) -> (), withCancel cancel: ((Error) -> ())?) {
let ref = Database.database().reference().child("MainTree").child("subTree1").child(uid)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists(){
guard let dictionaries = snapshot.value as? [String: Any] else {
completion([])
return
}
var Values = [UserData]()
let group = DispatchGroup()
dictionaries.forEach({ (key, value) in
group.enter()
let ref = Database.database().reference().child("MainTree").child("subTree2").child(key)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let userDictionary2 = snapshot.value as? [String: Any] else { return }
let user = UserData(dictionary: userDictionary2)
Values.append(user)
}) { (err) in
print("Failed to fetch all user data from database:", (err))
cancel?(err)
}
})
group.notify(queue: .main) {
print("loop done")
completion(Values)
}
}
}) { (err) in
print("Failed to fetch all data from database:", (err))
cancel?(err)
}
}
My Calling Function:
fetchAllInformation(uid: "JiRtkpIFLVFNgmNBpMj", completion: { (userdata) in
print("fetched all userdata! : ",userdata)
}) { (err) in
print("data fetch failed")
}
My Data Structure
struct UserData {
let uid: String
let username: String
init(dictionary: [String: Any]) {
self.uid = dictionary["id"] as? String ?? ""
self.username = dictionary["username"] as? String ?? ""
}
}
It might be a misunderstanding with asynchronous code. Right now the problem is that the array is turning up empty.