ios - 从 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ı"
},
当我写这个函数逻辑是这样的,
- 首先获取的类别
- 第二次获取的公司(本节中的延迟)
- 第三次获取的产品
我们需要访问确定哪个公司拥有类别的每个产品。
我希望我清楚地解释自己
解决方案
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) { ... }
推荐阅读
- c++ - Sprite 数组循环仅显示 1 个元素
- java - 推送通知未在 android 上显示
- javascript - 时刻js中的大写第一个字母
- c++ - 整数为 NULL 时无法打印 false,C++
- python - 在 tensorflow 上构建 CNN 时,如何指定要使用的卷积滤波器?
- delphi - 如何影响 2 个动画对象的 2 个角度?
- vuetify.js - 如何在具有多个选项的 Vuetify 自动完成菜单中隐藏复选框?
- arrays - ARDUINO:Serial.print 多字符元素
- hive - Hive 3.1 无法创建从内部/托管表复制架构的外部表
- certificate - 如何签署 .EXE 文件