0
func fetchAllUsers() {
    Database.database().reference().child("users").queryOrderedByKey().observeSingleEvent(of: .value) { (snapshot) in
        let sv = snapshot.value as! [String: AnyObject]
        //self.users.removeAll()
        for (_, value) in sv {
            if let uid = value["uid"] as? String {
                if uid != Auth.auth().currentUser!.uid {
                    if let firstname = value["firstname"] as? String, let lastname = value["lastname"] as? String, let username = value["username"] as? String, let bio = value["bio"] as? String {
                        let newUser = User(firstname: firstname, lastname: lastname, username: username, bio: bio, uid: uid)
                        self.users.append(newUser)
                    }
                }
            }
        }
    }
    Database.database().reference().removeAllObservers()
}

I get the user data so it retrieves it from the database, but whenever I try to append the user to my user array:

var users = [User]()

I print it after I call the function and it says it's empty. I'm confused because when I print it in the function it says it in there. So I really don't know what I'm doing wrong. I'm doing this for fun and for a test to send and retrieve data from a database (firebase).

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Data is loaded from Firebase (and from most modern cloud APIs) asynchronously. Since this may take some time, your main code continues to run. Then when the data is available from Firebase, your callback/completion handler is called with that data. For this reason, any code that needs the data from the database must be *inside* the completion handler, or be called from there. Have a look at these answers to learn more: https://stackoverflow.com/a/31316513, https://stackoverflow.com/a/43461660, https://stackoverflow.com/a/41797783, https://stackoverflow.com/a/58056434 – Frank van Puffelen Apr 28 '20 at 00:32
  • thank you! the threads that you gave me worked and now I am understanding better. – Devbool07 Apr 28 '20 at 02:29
  • Good to hear! This is an incredibly common problem to struggle with, so don't worry if you keep getting hit by it. Over time it gets less daunting. – Frank van Puffelen Apr 28 '20 at 02:30

0 Answers0