Problem using data from Firebase Database.

I have a problem with the data i get from the Firebase Database.

I´m getting the correct data from the database and i can directly print them out, but i can´t save the data on a variable or save the data in a structure.


Here is my code:


class viewController: UIViewController {
     var ref: DatabaseReference!
     var handle: DatabaseHandle!

     struct person {
          var name: String
          var ids: [String]
     }

     var personArray: [person] = []

     override func viewDidLoad() {
         super.viewDidLoad()
     
          ref = Database.databse().reference()

          handle = ref.child("path").observe(.childAdded, with: { (snapshot) in
               if let nameDatabase = snapshot.value as? String {
                  print(nameDatabase) //works
                  self.personArray.append(person(name: nameDatabase, ids: ["123"]))
               }
          })     
          print(personArray[0].name) //Error, array is empty
     }
}


I get the error: Fatal error: Index out of range.

But i have now idea, why the array is empty?!

If i save the data on a viriable and print it out in the if statement it works, but if I print it outsite the handle-function the variable is empty again.

I'm not good at Firebase something (generally Apple's forums are not good places for discussing third party libraries), but you may be misusing asynchronous operation.


In your code, you are passing a completion closure:


{ (snapshot) in
    if let nameDatabase = snapshot.value as? String {
        print(nameDatabase) //works
        self.personArray.append(person(name: nameDatabase, ids: ["123"]))
    }
}


The completion handler is evaluated later after data retrieval is completed.

Your code outlined:

    handle = ref.child("path").observe(.childAdded, with: yourCompletionHandler)
    //`observe(_:with:)`method returns immediately before yourCompletionHandler is evaluated
    print(personArray[0].name)
    //yourCompletionHandler will be evaluated later when the operation is completed


How to fix depends on how you want to use the result, but one thing sure is that you need to use the result only in the completion handler or after the handler is finished:

        handle = ref.child("path").observe(.childAdded, with: { (snapshot) in
            if let nameDatabase = snapshot.value as? String {
                print(nameDatabase) //works
                self.personArray.append(person(name: nameDatabase, ids: ["123"]))
                print(personArray[0].name)
                //Do other things you need to work with `personArray`...
            }
        })
Problem using data from Firebase Database.
 
 
Q