addSnapshotListener以仅获取Firebase集合中的更改

时间:2019-10-14 15:29:06

标签: swift firebase google-cloud-firestore listener

我添加了addSnapshotListener,例如:

            doc?.reference.collection("thread")
                .order(by: "created", descending: true)
                .addSnapshotListener(includeMetadataChanges: true, listener: { (threadQuery, error) in

            if let error = error {
                print("Error: \(error)")
                return
            } else {
                //print(threadQuery?.documents.count)
                    for message in threadQuery!.documents {
                        self.removeAllOverlays()
                        print("Data: \(message.data())")
                    }
            }
            })

每次将新文档添加到thread时,它都会加载完整线程。我该如何只提取添加到thread集合中的新文档?

1 个答案:

答案 0 :(得分:0)

为简单起见,假设有一个这样的用户集合

users
   doc_0
      name: "Pete"
   doc_1
      name: "Lewis"
   doc_2
      name: "Clark"

以下代码将观察者附加到用户节点,并在添加,修改或删除用户时通知我们。请注意,在第一次运行时,它将一次遍历每个用户,然后触发.add,这将使您最初填充一个数组。

func observeUserChanges() {
    let usersCollectionRef = self.db.collection("users")
    usersCollectionRef.addSnapshotListener { querySnapshot, error in
        guard let snapshot = querySnapshot else {
            print("Error fetching snapshots: \(error!)")
            return
        }

        snapshot.documentChanges.forEach { diff in
            let userName = diff.document.get("name") as? String ?? "No Name"
            if (diff.type == .added) {
                print("Added user: \(userName)")
            }
            if (diff.type == .modified) {
                print("Modified user: \(userName)")
            }
            if (diff.type == .removed) {
                print("Removed user: \(userName)")
            }
        }
    }
}

第一次运行时会输出

Added user: Pete
Added user: Lewis
Added user: Clark

然后,当添加新用户时,我们会看到

Added user: Ted

当Ted被删除时

Removed user: Ted