【问题标题】:UICollectionView + Firestore - Slow loadUICollectionView + Firestore - 加载缓慢
【发布时间】:2020-07-15 06:31:27
【问题描述】:

我想显示一些来自 Firestore 的数据,此时只有 3 个文档,有 3 个字段。

这是我在 viewDidLoad() 中调用的 loadData 函数:

    func loadDevices() {
        //clear devices array
        self.devices.removeAll()

        //get user's devices
        db.collection("devices").whereField("userId", isEqualTo: "{USER_ID}")
            .getDocuments() { (snap, err) in
                if let err = err {
                    print("Error getting devices: \(err)")
                } else {
                    for deviceItem in snap!.documents {
                        let data = deviceItem.data()
                        let device = Device(data: data)
                        self.devices.append(device)

                        self.collectionView.reloadData()

//                        DispatchQueue.main.async {
//                            self.collectionView.reloadData()
//                        }
                    }
                }
        }

从 Firestore 加载 3 条记录大约需要 2 秒。 如果我用硬编码数组测试它:

   func loadDevices() {
      devices.append(Device(id: "1", room: "test", userId: "dddd"))
      devices.append(Device(id: "2", room: "test2", userId: "dddd2"))
      devices.append(Device(id: "3", room: "test3", userId: "dddd3"))
   }

它会立即加载。 我的代码有问题吗?

【问题讨论】:

    标签: ios swift firebase google-cloud-firestore uicollectionview


    【解决方案1】:

    您的代码显然没有任何问题,但重要的是要注意,Firestore 操作将花费比将模拟数据添加到您的设备列表中更长的时间,原因是您的应用正在等待承诺已完成,查询结果异步到达,然后继续其操作,这需要一些时间。

    2 秒确实比您预期的要长,这可能是由于您与 Firestore 实例之间的物理距离导致的延迟问题。正如您在 Best Practices for Firestore documentation 上看到的那样,您应该考虑使用离您所在位置更近的实例,以减少延迟并提高性能。

    好消息是问题不在于您的数据复杂性或数据量,因此如果记录数量增加,并且由于 Firestore 查询非常快,那么获取数据的时间应该不会有很大变化更长的时间。

    【讨论】:

    • @kironet 我提供的答案对您有任何帮助吗?
    猜你喜欢
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 2018-07-06
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多