首页 > 解决方案 > 从 Firebase 获取太慢了

问题描述

我尝试从 firebase 获取数据,但我认为我的代码做错了。如果你能帮助我,我会在下面分享我的 fetch 方法和 firebase 结构,我会很高兴的

这是获取过程的第一部分

  DispatchQueue.main.async {

        Database.database().reference().child("Products/\(categoryUID)").observe(.value) { (snapshot) in
            if let result = snapshot.children.allObjects as? [DataSnapshot] {
                for child in result {
                    let companyId = child.key
                    self.getCompanyName(compID: companyId)
                    print(result)
                }
            }
        }

    }

在我得到公司之后,我将使用第二个获取方法来填充 tableView

 Database.database().reference().child("company").child(compID).observeSingleEvent(of: .value, with: { (snapshot) in
            guard let dictionary = snapshot.value as? [String: Any] else {return}
            self.company = Company(dictionary: dictionary, uid: compID)
            self.data.append(self.company!)
            print(self.data)
            self.tableView.reloadData()


        }) { (err) in
            print("Failed to fetch user for posts:", err)
        }

这个过程耗时过长,大约需要 15-20 秒。我找不到问题的原因

这是firebase结构

"Products" : {
"-LCJzPPR6knojTMm3sqd" : {
  "-LCJz95HuFlcrpGeRMa2" : {
    "-LCK3ysCZTUG7rBBZuRS" : {
      "product_detail" : "2325423542342",
      "product_image_url" : [ "https://firebasestorage.googleapis.com/v0/b/e-fiyat-69e44.appspot.com/o/p%2F1526140758172-1.jpg?alt=media&token=8e9c3feb-c722-427a-98e3-c02a27607874" ],
      "product_name" : "DENEME12",
      "product_price" : "234"
    }
  }
},

"category" : {
"-LCJzPPR6knojTMm3sqd" : {
  "imageUrl" : "https://firebasestorage.googleapis.com/v0/b/e-fiyat-69e44.appspot.com/o/category%2F1526139301086-Sandalye%20ve%20Koltuklar.png?alt=media&token=401ce15e-d08d-4487-9d79-67ec54e3f2b4",
  "name" : "Sandalye & Koltuklar"
},

"company" : {
"-LCJz95HuFlcrpGeRMa2" : {
  "imageUrl" : "https://firebasestorage.googleapis.com/v0/b/e-fiyat-69e44.appspot.com/o/company%2F1526139234155-cad.png?alt=media&token=9371db0c-d191-4277-93f6-871c43e758eb",
  "name" : "Cadı"
},

当我写这个函数逻辑是这样的,

我们需要访问确定哪个公司拥有类别的每个产品。

我希望我清楚地解释自己

标签: iosswiftfirebasefirebase-realtime-databasefetch

解决方案


1)这与主线程中不发生tableView reload非常相似。尝试为self.tableView.reloadData()添加DispatchQueue.main.async

func updateCompanies() {
    Database.database().reference().child("company").child(compID).observeSingleEvent(of: .value, with: { (snapshot) in
        guard let dictionary = snapshot.value as? [String: Any] else { return }

        self.company = Company(dictionary: dictionary, uid: compID)
        self.data.append(self.company!)
        print(self.data)

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

    }) { (err) in
        print("Failed to fetch user for posts:", err)
    }
}

2) 另外,如果数据库中有很多项目,请尽量不要一次获取所有项目。使用queryLimitedToLast

Database.database().reference().child("Products/\(categoryUID)").queryLimited(toLast: 20).observe(.value) { ... }

推荐阅读