我有一個 TableView 顯示來自我的 Firebase Firestore 服務器的檔案。我沒有在服務器上下載所有檔案,而是在用戶向下滾動 TableView 時分頁并下載更多檔案。如果服務器上有很多檔案,這非常有用。但是,如果只有幾個檔案,這意味著用戶需要滾動瀏覽的內容不夠多,則無限呼叫分頁程序,無限地從服務器查詢檔案。我怎樣才能解決這個問題?我知道 tableView willDisplayForRowAt 中的以下行有問題:
if (indexPath.row == fileArray.count - 1)
我只是不知道如何解決它。
struct FileIdentifierStruct {
var fileName = String()
var fileDate = String()
}
var fileArray = [FileIdentifierStruct]()
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// Trigger pagination when scrolled to last cell
if (indexPath.row == fileArray.count - 1) {
print("Calling paginate")
paginate()
}
}
func paginate() {
print("paginate function was called")
// This is the main pagination code
query = query.start(afterDocument: documents.last!)
// For some reason calling getData here enters an infinite loop until the view is exited
getData()
}
func getData() {
print("getData was called")
query.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err.localizedDescription)")
let alert = SCLAlertView()
alert.showError("ERROR", subTitle: "The following error occured while trying to retrieve the documents: \(err.localizedDescription)")
} else {
querySnapshot!.documents.forEach({ (document) in
// let data = document.data() as [String: AnyObject]
// Set up the data modal here
let date = document.get("Date") as? String ?? ""
let id = document.documentID
let fileItem = FileIdentifierStruct(fileName: id, fileDate: date)
self.fileArray = [fileItem]
self.documents = [document]
})
self.filesTableView.reloadData()
self.filesTableView.showDefault()
}
}
}
uj5u.com熱心網友回復:
您可以添加一個布爾標志:
var hasReceivedZeroResults = false
然后在您收到檔案串列時在您的 getData() 函式中:
self.hasReceivedZeroResults = querySnapshot!.documents.isEmpty
最后在 paginate() 函式的頂部插入:
guard !hasReceivedZeroResults else { return }
uj5u.com熱心網友回復:
這里的挑戰是 Firebase Firestore 中的實際資料集具有未知數量的資料,因此在不知道“最后一行”是什么的情況下,沒有簡單的方法可以知道您在分頁時顯示的是“最后一行”
幾個選項:
一個常見的解決方案是使用另一個集合來存盤您正在顯示的集合的檔案計數,并觀察該集合的更改,以便您始終知道最后一行是什么,并且在您顯示時不能嘗試加載更多資料最后一行資料。
例如,假設您的應用顯示用戶
users_collection
user_0
name: "Jay"
user_1
name: "Cindy"
user_2
name: "Larry"
然后是一個跟蹤用戶數量的集合
document_count
users_collection
count: 3
將觀察者添加到 document_count、users_collection 并在添加或洗掉用戶時增加/減少該計數,保留一個類 var 以使該計數可用于函式,呼叫它var totalRows = 0
然后,當用戶滾動到陣列中的最后一行并且有更多可用資料時,只需要呼叫 paginate
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt...
// Trigger pagination when scrolled to last cell & there's more rows
if (indexPath.row == fileArray.count - 1 && lastRowDisplayedIndex < self.totalRows) {
paginate()
}
}
請注意,這假設您正在跟蹤 Firestore 中的哪些行以某種形式顯示。
另一種選擇是記錄在最后一次查詢中讀取了多少檔案
query.getDocuments() { (querySnapshot, err) in
self.lastReadCount = snapshot.count
那么當用戶嘗試滾動時,僅當 lastReadCount 等于您要顯示的數字時才會呼叫分頁。
例如
假設您想一次顯示 5 個用戶。如果顯示 5 個用戶,則呼叫 paginate 以嘗試再讀取 5 個,如果僅讀取 3 個,則 self.lastReadCount 將為 3,并且您會知道您在串列的末尾,所以不要呼叫 paginate。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/447189.html
