【问题标题】:How can i change the whereField value of shapshotListener properly in swift?如何在 swift 中正确更改 shapshotListener 的 whereField 值?
【发布时间】:2021-01-10 03:06:27
【问题描述】:

我需要更改“snapshotListener”查询中的whereField变量值。

即使我在更改之前调用代码listener?.remove,根据先前查询条件的快照正在重新开始侦听,而我正在使用新的whereField 值调用“shapshotListener”。

同时,根据新查询条件的快照也开始监听。

所以当文档有任何变化时,我会收到 2 个不同的快照。

我想用代码解释一下:

第 1 步(认为 UserID 是 111)

listener = Firestore.firestore().collection("Annotations").whereField("UserID", isEqualTo: \(UserID)).addSnapshotListener { (snapshot, error) in

        if error != nil {}else {
            if snapshot?.isEmpty == false && snapshot != nil {
                for document in snapshot!.documents {
                    if let snapshotUserID = document.get("UserID") as? String {

                        print("snapshotUserID: \(snapshotUserID)")
                        print("UserID: \(UserID)")
                    }
                }
            }
        }
    }

第 2 步

listener?.remove

第 3 步

UserID = 112

第四步

listener = Firestore.firestore().collection("Annotations").whereField("UserID", isEqualTo: \(UserID)).addSnapshotListener { (snapshot, error) in

        if error != nil {}else {
            if snapshot?.isEmpty == false && snapshot != nil {
                for document in snapshot!.documents {
                    if let snapshotUserID = document.get("UserID") as? String {

                        print("snapshotUserID: \(snapshotUserID)")
                        print("UserID: \(UserID)")
                    }
                }
            }
        }
    }

现在,我有两个 UserID 文档的 2 个 shapshotListener。

想如果UserID为111的文档有任何变化,在控制台中会这样写;

快照用户 ID:111

用户 ID:112

如何正确更改 shapshotListener 的查询参数?

【问题讨论】:

    标签: swift firebase google-cloud-firestore listener snapshot


    【解决方案1】:

    在附加了侦听器并接收结果时,无法更改查询。您现在正在做的就是您能做的最好的事情 - 删除侦听器,构建新查询,然后向该查询添加新侦听器。如果您不想处理来自新查询的任何重复数据,您将弄清楚如何跳过您不想处理的快照。

    【讨论】:

      猜你喜欢
      • 2015-09-07
      • 1970-01-01
      • 2015-12-16
      • 2021-11-02
      • 1970-01-01
      • 2019-09-08
      • 2023-04-08
      • 2022-10-20
      • 1970-01-01
      相关资源
      最近更新 更多