0

I'm trying to append "the retrieved data -Keys- from firebase" into an array but it doesn't work

This is the for loop output #2 the retrieved keys

This the keys from firebase

This is the code

let ref = Database.database().reference()
        ref.child("Faculty ").observe(.value, with: { (snapshot) in
            if let result = snapshot.children.allObjects as? [DataSnapshot] {
                for child in result {
                    let FacultyName = child.key as! String
                    print(FacultyName)
                    self.NamesofFac.append(FacultyName)

                }
            }
        })

        for i in 0...self.NamesofFac.count {
            print(self.NamesofFac.count)
            print(" line")
            print(self.NamesofFac)

1 Answer 1

1

The problem you are having is the Firebase Observe function give a callback in the form of a (snapshot).

It takes a bit of time to go to the web to get the data, therefore, firebase returns the data asynchronously. Therefore your code in your for loop will run before your firebase data has been returned. At the time your for loop code runs the array is still blank. But the for loop code in a separate function as you see in my sample code and call it straight after your for loop inside your firebase observe call.

Try this instead:

override func viewDidLoad() {
    getFirebaseData()
}
func getFirebaseData() {
    let ref = Database.database().reference()
    ref.child("Faculty ").observe(.value, with: { (snapshot) in
        if let result = snapshot.children.allObjects as? [DataSnapshot] {
            for child in result {
                let FacultyName = child.key as! String
                print(FacultyName)
                self.NamesofFac.append(FacultyName)

            }
            printNames()
        }
    })
}



func printNames() {
    for i in 0...self.NamesofFac.count {
        print(self.NamesofFac.count)
        print(" line")
        print(self.NamesofFac)
    }
}

This was it won't print the names until they have been fully loaded from firebase.

PS: Your naming conventions are incorrect. You seem to be naming variables with a capital letter. Variables should be camel case. Classes should start with a capital.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.