gpt4 book ai didi

swift - addSnapshotListener 仅获取 firebase 集合中的更改

转载 作者:行者123 更新时间:2023-11-30 10:34:28 25 4
gpt4 key购买 nike

我添加了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 集合中添加的新文档?

最佳答案

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

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

以下代码将向用户节点附加一个观察者,并在添加、修改或删除用户时通知我们。请注意,第一次运行时,它将迭代每个用户,一次一个并触发 .added,这将允许您最初填充一个数组。

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

关于swift - addSnapshotListener 仅获取 firebase 集合中的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58379869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com