gpt4 book ai didi

swift - 在 Swift 中写入 Firestore 时,如何将 addSnapshotListener 方法与 getDocument 一起使用?

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

我正在尝试从 Firebase Firestore 获取数据。我成功地获取了数据,但是,我将其显示在 UITableView 中,并且我需要它来实时获取数据。我正在使用 getDocuments 方法,但无法添加快照监听器,因为我无法覆盖 getDocuments 参数。

func loadPartiesDataFromFirebase() {
let db = Firestore.firestore()
db.collection("parties").getDocuments() { snapshot, err in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in (snapshot!.documents) {
let title = document.data()["title"] as? String ?? "New Party"
let location = document.data()["location"] as? String ?? "No Location"
let date = document.data()["date"] as? String ?? "No Date"
let startTime = document.data()["startTime"] as? String ?? "No Start Time"
let endTime = document.data()["endTime"] as? String ?? "No End Time"

self.parties.append(Party(title: title, location: location, date: date, startTime: startTime, endTime: endTime))
}
}

self.yourPartiesTableView.reloadData()
}

我希望它能够持续实时显示来自 Firestore 的数据。我怎样才能在 Swift 中做到这一点?

最佳答案

您需要向集合添加一个监听器。

    let db = Firestore.firestore()
let listener = db.collection("parties").addSnapshotListener { (snapshot, error) in
switch (snapshot, error) {
case (.none, .none):
print("no data")
case (.none, .some(let error)):
print("some error \(error.localizedDescription)")
case (.some(let snapshot), _):
print("collection updated, now it contains \(snapshot.documents.count) documents")
}
}

此外,您可以存储对监听器的引用,并在不需要时将其删除。

    listener.remove()

关于swift - 在 Swift 中写入 Firestore 时,如何将 addSnapshotListener 方法与 getDocument 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56177500/

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