我希望能够获取Firebase子级并将其显示在TableView中

时间:2019-06-24 18:27:08

标签: ios arrays swift firebase firebase-realtime-database

我正在尝试从Firebase实时数据库中获取“订单”节点。当我上传到我的Orders节点时,我将childByAutoID()作为嵌套内部的键上传,以便以后可以检索它。我只想从Orders节点读取所有childByAutoIDs()并在TableView Cell中显示它们的每个内容。有什么帮助吗?,谢谢!

我尝试从我的数据库文件中获取该函数,并在viewDidAppear方法中向我的对象加载数据。并在TableView CellForRowAt闭包内再次调用

//This is the Database file function
func getAllOrders(handler: @escaping (_ orderArray: 
[AdminOrdersObject]) -> ()) {
    var orderArray = [AdminOrdersObject]()
    REF_ORDERS.observe(DataEventType.value) { (orderSnapshot) in
        guard let orderSnapshot = 
orderSnapshot.children.allObjects as? [DataSnapshot] else {return}
        for order in orderSnapshot {

                let orderID = order.childSnapshot(forPath: 
"OrderID").value as! String
                let name = order.childSnapshot(forPath: 
"Name").value as! String?
                let time = order.childSnapshot(forPath: 
"Time").value as! String?
                let total = order.childSnapshot(forPath: 
"Total").value as! Double?
                let userID = order.childSnapshot(forPath: 
"UserID").value as! String?
                let drinks = order.childSnapshot(forPath: 
"Drinks").value as! [String]
                let meals = order.childSnapshot(forPath: 
"Meals").value as! [String]
                let deals = order.childSnapshot(forPath: 
"Deals").value as! [String]

                let fullOrder = AdminOrdersObject(meals: meals, 
drinks: drinks, deals: deals, name: name!, time: time!, total: 
total!, orderID: orderID, userID: userID!)
                orderArray.append(fullOrder)
        }
        handler(orderArray)
    }
}

//This is my empty initialized object
var ordersArray = [AdminOrdersObject]()


// This is the ViewWillAppear function
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

        DataBaseService.instance.REF_ORDERS.observe(.value) { 
(snapshot) in
            DataBaseService.instance.getAllOrders(handler: { 
(returnedArray) in
                self.ordersArray = returnedArray
                self.OrdersTableView.reloadData()
            })
       }
 }

//This is the TableView CellForRowAt function
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: 
 IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: 
 "OrderCellDetail") as? OrderCellDetail else {
        return UITableViewCell() }
    var order = ordersArray[indexPath.row]

    DataBaseService.instance.REF_ORDERS.observe(.value) { 
 (snapshot) in
            DataBaseService.instance.getAllOrders { 
(returnedArray) in
                cell.configureCell(Name: order.name, Time: 
order.time, Total: String(order.total))
            }
    }
    return cell
}

它在数据库文件中崩溃,显示为“无法将NSNull转换为NSString”

0 个答案:

没有答案