0

I am new to Firebase and I am trying to get the children from a DataSnapshot and add the keys to a list. But I am getting an error. Am i not unwrapping the data correctly or what am i doing wrong?

    var arr: Array<String> = []

override func viewDidLoad() {
    super.viewDidLoad()

    populateArray()


    print(arr)

    func populateArray(){

    ref.child("Sept24 - Oct 24").observeSingleEvent(of: .value, with: { (snapshot) in
      print(snapshot.childrenCount)
        let enumerator = snapshot.children
        while let rest = enumerator.nextObject() as? DataSnapshot {
            //print(rest.key)
            self.arr.append(rest.key)

        }
        DispatchQueue.main.async{
            self.sideMenuTable.reloadData()
        }

    })
   print(arr)

}

arr is a global array with type string and i am calling populateArray() in the viewDidLoad() function.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Zach
  • 33
  • 1
  • 6
  • Which line exactly is causing the error? And update your question to include the declaration for `arr`. – rmaddy Oct 01 '17 at 20:19
  • In the ref.child line. This is the error "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" – Zach Oct 01 '17 at 20:24
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Tamás Sengel Oct 01 '17 at 21:57
  • What data do you have at `ref.child("Sept24 - Oct 24")`? You can get this by clicking the "Export JSON" link in your [Firebase Database console](https://console.firebase.google.com/project/_/database/data). – Frank van Puffelen Oct 01 '17 at 22:16
  • They are all strings – Zach Oct 01 '17 at 22:21
  • Where are you setting the `ref`? – 3stud1ant3 Oct 02 '17 at 03:12
  • Thanks! Thats was the issue. I was declaring in another function and i thought i had it global. – Zach Oct 02 '17 at 04:25
  • You have another issue - *both* of the the print(arr) lines will execute before the array is populated (sometimes). – Jay Oct 03 '17 at 12:10
  • @Jay how do I get it to print(arr) after the lines execute – Zach Oct 17 '17 at 02:45
  • Firebase is asynchronous and it's data becomes valid only within the closure after the Firebase call. In your case, you call populateArray and then immediately print(arr) but that statement will execute *before* Firebase has returned data and populated the array. So, within the closure, immediately following the While loop that populates the array, you can call print(arr). Note that the print(arr) within populateArray will also execute before Firebase has had a chance to return data. – Jay Oct 17 '17 at 17:21

0 Answers0