ios - 在获取数据 Firebase/Swift 之前加载 TableView

标签 ios swift firebase

我有一个 FireBase 数据库,里面有一个产品表和另一个带有这些产品 ID 的订单表,我想做的是根据订单表内的 ID 从产品表中获取产品,因为FireBase 只允许我一个一个地获取产品,在我获取订单表中引用的所有产品之前加载我的表格 View 。

我是怎么做到的:

struct Product: Decodable, Encodable{
    var id: String?
    var ref: String
    var description: String
    var type: String
    var price: String
    var qtyOrdred:Int?
}

struct Order:Decodable, Encodable {

    var id: String?
    var isValide: Bool
    var madeBy: String
    var info: String?
    var ordredProd: [OrderedProduct]

}

struct OrderedProduct:Decodable, Encodable {
    var id: String
    var qty: Int
}

 func getData(completion: @escaping ([Product])->Void){
        var allProduct = [Product]()
        for product in orderedProduct {
            getProductWithKey(qty: product.qty, key: product.id) { (p) in
                print(p.ref)
                allProduct.append(p)
            }
}
}

func getProductWithKey(qty: Int,key: String, completion: @escaping (Product)->Void) {
    Database.database().reference().child("products").child(key).observeSingleEvent(of: .value) { (snap) in
        if let productObject = snap.value as? [String: Any]
        {
            if let ref  = productObject["ref"],
                let price  = productObject["price"],
                let type = productObject["type"],
                let description = productObject["description"],
                let id = productObject["id"]{
                let p = Product(id: id as? String, ref: ref as! String, description: description as! String, type: type as! String, price: price as! String, qtyOrdred: qty)
                completion(p)
            }
        }
    }
}

我这样调用它:

override func viewWillAppear(_ animated: Bool) {
        self.getData { (ps) in
            print(ps)
            self.tableView.reloadData()
        }
    }

问题是它总是打印一个空数组,而我的tableview数据永远不会改变

最佳答案

你没有从getData完成返回,你需要一个调度组

let g = DispatchGroup()
func getData(completion: @escaping ([Product])->Void){
     var allProduct = [Product]()
     for product in orderedProduct { 
        g.enter()
        getProductWithKey(qty: product.qty, key: product.id) { (p) in
            print(p.ref)
            allProduct.append(p)
            g.leave()
        }
     }  
     g.notify(queue:.main) {
        completion(allProduct)
     }
}

关于ios - 在获取数据 Firebase/Swift 之前加载 TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58187511/

相关文章:

java - Firebase removeValue() 函数未删除正确的值

node.js - 如何使用 Cloud Functions for Firebase 获取子值的键?

iOS:当应用程序被带到前台时刷新数据

ios - NSSearchPathForDirectoriesInDomains 在模拟器上工作但不在设备上工作

ios - 支持应用程序和扩展程序的 Swift 库

ios - 分段按钮控制

ios - 集成 FirebasePhoneAuthUI 进行电话号码身份验证

ios - JSON Alamofire POST 请求错误 - 元组类型的值

ios - 未收到来自 CloudKit 订阅的推送通知

ios - 以秒为单位转换 Firebase 时间戳?