0

I have these arrays that I want to display in a tableView:

private var firOrder = [String]()
private var firDate = [Int]() 

I try to get and append the data like this:

override func viewDidLoad() {
    ref = Database.database().reference() ref?.child("users").child(user).child("Orders").observe(.value, with: { (snapshot) in
        let values = snapshot.value as? [String: AnyObject]
        let order = values!["Order"] as! String
        let date = values!["Date"] as! Int
        print("order \(order)") //This prints correctly
        print("date \(date)")  //This prints correctly

        self.firOrder.append(order)   
        self.firDate.append(date)
    })

    print(firOrder) //This prints empty and does not append to array.   
    print(firDate) //This prints empty and does not append to array
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Anvil
  • 1,745
  • 1
  • 11
  • 16
  • Any code that need the data from `snapshot ` needs be to (invoked from) **inside** the closure that defines `snapshot`. Also see https://stackoverflow.com/questions/43823808/access-firebase-variable-outside-closure, https://stackoverflow.com/questions/39067196/using-variables-outside-of-completion-block, https://stackoverflow.com/questions/28390635/can-swift-return-value-from-an-async-void-returning-block, https://stackoverflow.com/questions/46229172/completion-handler-firebase-observer-in-swift/46229369#46229369 – Frank van Puffelen Jul 31 '18 at 01:56

1 Answers1

2

Because the call is asynchronous , you need to reload the table inside the callback where the data returns

self.firOrder.append(order)   
self.firDate.append(date)
self.tableView.reloadData()
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • Thank you for your answer. I had the `tableView.reloadData()` in `viewDidAppear` I get the error: "Thread 1: Fatal error: Index out of range" when trying to populate the tableView with: `firOrder[indexPath.row]` – Anvil Jul 31 '18 at 10:51
  • which count you supply in numberOfRows ?? , also do you use both arrays as the dataSource of the table ?? – Shehata Gamal Jul 31 '18 at 10:52
  • 1
    Ahh! Well spotted!! I used the wrong count in `numberOfRows` Thanks a lot. – Anvil Jul 31 '18 at 10:58