I am appending user info from Firebase into an array but it seems like the array(usersArray) is empty in all prints after the loop. The array is declared outside the function. Any ideas why? Thank you.
func fetchAllUsers(completion: @escaping (_ message: String) -> Void){
//User or advertiser?
let uid = Auth.auth().currentUser?.uid
Database.database().reference(withPath: "Advertiser").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists(){
myAdvertiserVar.advertiser = true
// Fetch all users
self.ref?.child("Users").observe(DataEventType.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.nameLabel = dictionary["Username"] as? String
user.occupationLocation = dictionary["Occupation"] as? String
user.ageLabel = dictionary["Age"] as? String
user.infoText = dictionary["Bio"] as? String
user.emailText = dictionary["email"] as? String
let email = user.emailText
let ref = Database.database().reference().child("Users")
ref.queryOrdered(byChild: "email").queryEqual(toValue: email).observeSingleEvent(of: .childAdded, with: { (snapshot) in
user.toId = snapshot.key
})
self.usersArray.append(user)
}
})
dump(self.usersArray) //This print is empty
completion("FetchAllUsers")
}
}