Neccer
Neccer

Reputation: 136

How to populate tableView with data from childByAutoID

I have a FirebaseStructure like so:

 "users" : {    "OpeHS4UhH6YWcK4aPHJWumueCQP2" : {
      "Orders" : {
        "Date" : {
          "-LQYDWAKlzTrlTtO1Qiz" : 1541410526186,
          "-LQYspEghK3KE27MlFNE" : 1541421618601,
          "-LQsILjpNqKwLl9XBcQm" : 1541764115618
        },
        "Order" : {
          "-LQYDWAKlzTrlTtO1Qiy" : "1 Tomato, 3 Orange, 2 Banana",
          "-LQYspEfZaJIt-PaAvYa" : "1 Banana, 9 Apple, 2 Tomato",
          "-LQsILjpNqKwLl9XBcQl" : "1 Apple"
        }
      }
    }    

I want to display the order history in a tableView
How can I populate the tableView with the "Order" without the childByAutoID?
I have tried this, but it comes up empty:

class OrderHistoryTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var orderDateHistoryArray = [Double]()
    var orderItemsHistoryArray = [String]()

    @IBOutlet var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

      getOrderHistory()
    }


     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return orderItemsHistoryArray.count            
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "OrderHistoryCell") as! OrderHistoryTableViewCell
        cell.orderHistoryItemsLabel.text = orderItemsHistoryArray[indexPath.row]
        return cell
    }

    func getOrderHistory() {
        //Get userinfo from database
    let uid = Auth.auth().currentUser!.uid
    let orderDateHistoryRef = Database.database().reference().child("users/\(uid)/Orders/")
        orderDateHistoryRef.observeSingleEvent(of: .value, with: { (snapshot) in
            // Get user value
    let value = snapshot.value as? NSDictionary
    let orderItem = value?["Order"] as? String ?? ""
    self.orderItemsHistoryArray += [orderItem]

    print(snapshot)
    print(orderItem)

    self.tableView.reloadData()
    // ...
        }) { (error) in
            print(error.localizedDescription)
        }
    }
}

Upvotes: 2

Views: 23

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100533

Order is a Dictionary not a String

if  let orderItem = value?["Order"] as? [String:String] {
   self.orderItemsHistoryArray += Array(orderItem.values)
}

Upvotes: 1

Related Questions