【发布时间】:2018-04-23 12:49:35
【问题描述】:
在我的应用中,我尝试使用以下代码从 Firestore 对我的数据(每页 10 个帖子)进行分页,
import UIKit
import FirebaseFirestore
class Home: UITableViewController {
var postArray = [postObject]()
let db = Firestore.firestore()
var page : DocumentSnapshot? = nil
let pagingSpinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
override func viewDidLoad() {
super.viewDidLoad()
loadFirstPage()
}
func loadFirstPage(){
// Get the first 10 posts
db.collection("POSTS").limit(to: 10).addSnapshotListener { (snapshot, error) in
if snapshot != nil {
self.postArray = (snapshot?.documents.flatMap({postObject(dec : $0.data())}))!
// Save the last Document
self.page = snapshot?.documents.last
self.tableView.reloadData()
}
}
}
func loadNextPage(){
// get the next 10 posts
db.collection("POSTS").limit(to: 10).start(afterDocument: page!).addSnapshotListener { (snapshot, error) in
if snapshot != nil {
for doc in (snapshot?.documents)! {
self.postArray.append(postObject(dec: doc.data()))
}
self.page = snapshot?.documents.last
self.tableView.reloadData()
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as? postCell
// display data
cell?.textLabel?.text = postArray[indexPath.row].name
return cell!
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// check index to load next page
if indexPath.row < (self.postArray.count){
pagingSpinner.startAnimating()
pagingSpinner.color = UIColor.red
pagingSpinner.hidesWhenStopped = true
tableView.tableFooterView = pagingSpinner
loadNextPage()
}
}
}
但我遇到了以下问题:
- 如果我第一次开始发布内容(FireStore 没有 数据)来自其他设备的应用程序将崩溃,因为 page 将始终为 nil。
- 我尝试通过控制台插入 10 个帖子并在我检查应用程序时 开始使用我的表格视图向下滚动它会崩溃相同 原因 page 为 nil。
我想知道为什么会发生这种情况,尽管我将最后一个 Sanpshot 文档保存为分页光标!有没有更好的为什么用 Swift 实现分页
【问题讨论】:
-
我最初的印象可能是您遇到了竞争情况,您的应用可能会在完成获取第一个快照之前尝试调用“loadNextPage”(因此页面将为 nil)。尝试添加一些控制台日志以查看是否是这种情况。
-
@ToddKerpelman 检查问题后,正如您提到的那样,滚动带有条件
if indexPath.row < (self.postArray.count)的 uitableview 将始终在获取第一个快照之前触发“loadNextPage”
标签: ios swift firebase pagination google-cloud-firestore