對于我的聊天,我在一個類中有一個函式,我在“訊息”集合上創建了一個 SnapshotListener。出于性能考慮,我將回傳的檔案數量限制為 20。我想做的是更改此限制并為每次單擊按鈕添加 20 個更多檔案,并使 SnapshotListener 現在調整為這 40 個檔案。我怎樣才能做到這一點?當它不在 SnapshotListener 中時很容易,但我該如何使用它呢?
func readAllMessages() {
let docRef = ref.collection("discussions").document(id)
docRef.collection("messages")
.order(by: "dateCreated", descending: true)
.limit(to: 20)
.addSnapshotListener { (snap, err) in
guard let documents = snap?.documents.reversed() else {
print(err!.localizedDescription)
return
}
self.messages = documents.compactMap { (QueryDocumentSnapshot) -> Message_M? in
return try? QueryDocumentSnapshot.data(as: Message_M.self)
}
}
}
uj5u.com熱心網友回復:
Firestore 中的查詢是不可變的,因此無法更改已附加偵聽器的查詢。您必須使用 new 創建一個新查詢,limit(to: 40)然后為其附加一個新的偵聽器。
如果您啟用了磁盤持久性(默認情況下),前 20 個檔案將來自本地快取,因此您應該只為 20 個新檔案收取檔案讀取費用。
uj5u.com熱心網友回復:
我幾乎解決了我的問題。使用此代碼它可以作業,但是一旦我寫了一條新訊息(檔案),請求回傳的數量就會回到它的來源(對于我的測驗,limitToRead = 2)。因此,如果我只單擊按鈕,它就可以作業(我在聊天中收到了 2、4、6、8 等訊息,順序正確)但是一旦我向其他用戶發送訊息或收到訊息(a訊息集合上的新寫入)它回傳到 2 條訊息。
我修改后的功能:
func readAllMessages(limitToRead: Int) {
let docRef = ref.collection("discussions").document(id)
docRef.collection("messages")
.order(by: "dateCreated", descending: true)
.limit(to: limitToRead)
.addSnapshotListener { (snap, err) in
guard let documents = snap?.documents.reversed() else {
print(err!.localizedDescription)
return
}
self.messages = documents.compactMap { (QueryDocumentSnapshot) -> Message_M? in
return try? QueryDocumentSnapshot.data(as: Message_M.self)
}
}
}
我的看法 :
...
@State private var limitToRead: Int = 2
init(...) {
...
messageData.readAllMessages(limitToRead: 2)
...
}
...
Button {
limitToRead = 2
messageData.readAllMessages(limitToRead: limitToRead)
} label: {
Text("Tap me!")
.padding()
.foregroundColor(.white)
.background(.red)
}
...
正如弗蘭克所建議的,我如何在這個函式中創建一個新的查詢和新的偵聽器并將我的訊息陣列附加到它?
更新 :
我也試過這個=相同的結果:
func readAllMessages(limitToRead: Int, newListener: Bool) {
let docRef = ref.collection("discussions").document(id)
var listener = docRef.collection("messages")
.order(by: "dateCreated", descending: true)
.limit(to: limitToRead)
.addSnapshotListener { (snap, err) in
guard let documents = snap?.documents.reversed() else {
print(err!.localizedDescription)
return
}
self.messages = documents.compactMap { (QueryDocumentSnapshot) -> Message_M? in
return try? QueryDocumentSnapshot.data(as: Message_M.self)
}
}
if newListener == true {
listener.remove()
listener = docRef.collection("messages")
.order(by: "dateCreated", descending: true)
.limit(to: limitToRead)
.addSnapshotListener { (snap, err) in
guard let documents = snap?.documents.reversed() else {
print(err!.localizedDescription)
return
}
self.messages = documents.compactMap { (QueryDocumentSnapshot) -> Message_M? in
return try? QueryDocumentSnapshot.data(as: Message_M.self)
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/356464.html
標籤:ios 火力基地 谷歌云firestore 迅捷
下一篇:自定義單元格中自定義UITableViewCell內的多個UIStackViews沒有Storyboard不起作用
