我正在尝试使用查询游标加载我的Firestore数据库,以使其看起来像无限滚动。当我查询第一个批处理时一切正常,但是当我滚动我的应用程序时崩溃并给我这个错误:
致命错误:在隐式展开可选值时意外发现nil
我知道这意味着什么,但是我找不到正确的方法。错误是从此行开始的:
queryRef = db.collection("Ingredients").start(afterDocument: lastDocument).limit(to: 2)
这是我的代码:
var fetchMoreIngredients = false
var reachEnd = false
let leadingScreensForBatching: CGFloat = 3.0
var ingredients = [Ingredients]()
var lastDocument:DocumentSnapshot!
func loadData(completion: @escaping(_ ingredients:[Ingredients])->()){
let db = Firestore.firestore()
let lastIngredient = self.ingredients.last
var queryRef: Query!
if lastIngredient == nil{
queryRef = db.collection("Ingredients").limit(to: 2)
}else{
queryRef = db.collection("Ingredients").start(afterDocument: lastDocument).limit(to: 2)
}
queryRef.getDocuments(){
querySnapshot, error in
if let error = error {
print("\(error.localizedDescription)")
}else if let querySnapshot = querySnapshot {
if (querySnapshot.isEmpty == false){
let res = querySnapshot.documents.compactMap({Ingredients(dictionary: $0.data())})
self.ingredients.append(contentsOf: res)
}
}
return completion(self.ingredients)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let off = scrollView.contentOffset.y
let off1 = scrollView.contentSize.height
if off > off1 - scrollView.frame.height{
if !fetchMoreIngredients && !reachEnd{
beginBatchFetch()
}
}
}
func beginBatchFetch(){
fetchMoreIngredients = true
loadData{ newIngredients in
self.ingredients.append(contentsOf: newIngredients)
self.reachEnd = newIngredients.count == 0
self.fetchMoreIngredients = false
self.tableView.reloadData()
}
}