提取的文档正在替换表视图中以前加载的文档



我正在使用以下代码从swift iOS中的firestore数据库中获取数据。但当我滚动时,加载的新数据正在替换表视图中先前加载的数据。我正在努力解决这个问题,但到目前为止没有任何好处。

所需的结果是将新文档添加到表视图中先前的文档列表中

下面是我正在实现的代码。如果需要更多信息,请让我知道

代码

fileprivate func observeQuery() {
fetchMoreIngredients = true
//guard let query = query else { return }
var query1 = query
stopObserving()
if posts.isEmpty{
query1 = Firestore.firestore().collection("posts").order(by: "timestamp", descending: true).limit(to: 5)
}
else {
query1 = Firestore.firestore().collection("posts").order(by: "timestamp", descending: true).start(afterDocument: lastDocumentSnapshot).limit(to: 2)
//  query = db.collection("rides").order(by: "price").start(afterDocument: lastDocumentSnapshot).limit(to: 4)
print("Next 4 rides loaded")
print("hello")
}
// Display data from Firestore, part one
listener = query1!.addSnapshotListener { [unowned self] (snapshot, error) in
guard let snapshot = snapshot else {
print("Error fetching snapshot results: (error!)")
return
}
let models = snapshot.documents.map { (document) -> Post in
if let model = Post(dictionary: document.data()) {
return model
} else {
// Don't use fatalError here in a real app.
fatalError("Unable to initialize type (Post.self) with dictionary (document.data())")
}
}
self.posts = models
self.documents = snapshot.documents
if self.documents.count > 0 {
self.tableView.backgroundView = nil
} else {
self.tableView.backgroundView = self.backgroundView
}
self.tableView.reloadData()
self.fetchMoreIngredients = false
self.lastDocumentSnapshot = snapshot.documents.last
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let off = scrollView.contentOffset.y
let off1 = scrollView.contentSize.height
if off > off1 - scrollView.frame.height * leadingScreensForBatching{
if !fetchMoreIngredients && !reachEnd{
print(fetchMoreIngredients)
//  beginBatchFetch()
// query = baseQuery()
observeQuery()
}
}
}

不调用snapshot.documents,而是调用snapshot.dococumentChanges。这会返回文档更改的列表(.addd、.modified或.removed(,并允许您根据需要在本地数组中添加、删除或修改它们…未经测试的代码只是一个想法…

snapshot.documentChanges.forEach() { diff in
switch diff.type {
case .added:

if let model = Post(dictionary: diff.document.data()){
self.posts.append(model)
}else {
// Don't use fatalError here in a real app.
fatalError("Unable to initialize type (Post.self) with dictionary (document.data())")
}
case .removed:
// add remove case
case .modified:
// add modify case
}
}

最新更新