【发布时间】:2020-08-09 21:12:26
【问题描述】:
我正在运行代码以在 swift iOS 聊天应用程序中加载聊天。聊天应用程序中的问题是在运行应用程序时函数 paginateData() 中的“query in else{}”,第一个“query in if{}”按预期顺利运行,但在另一个没有运行。我正在使用 firestore 数据库来实现聊天。 我的目标是对聊天室中的聊天进行分页。如果需要更多信息,请告诉我。
代码
func paginateData() {
fetchingMore = true
var query: Query!
if messages.isEmpty {
query = Firestore.firestore().collection("messageRoom").document(messageRoomIdFinal).collection("messages").order(by: "timestamp", descending: false).limit(to: 20)
print("First 20 Messages loaded")
} else {
query = Firestore.firestore().collection("messageRoom").document(messageRoomIdFinal).collection("messages").order(by: "timestamp", descending: false).start(afterDocument: lastDocumentSnapshot).limit(to: 7)
print("Next 7 Messages loaded")
}
query.addSnapshotListener { (snapshot, err) in
if let err = err {
print("\(err.localizedDescription)")
} else if snapshot!.isEmpty {
self.fetchingMore = false
return
} else {
snapshot!.documentChanges.forEach { diff in
if (diff.type == .added) {
let snap = diff.document
let aMessage = Message(withSnap: snap)
self.messages.append(aMessage)
DispatchQueue.main.async {
self.collectionView.reloadData()
let indexPath = IndexPath(item: self.messages.count - 1, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .bottom, animated: true)
}
}
if (diff.type == .modified) {
let docId = diff.document.documentID
DispatchQueue.main.async {
self.collectionView.reloadData()
let indexPath = IndexPath(item: self.messages.count - 1, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .bottom, animated: true)
}
//update the message with this documentID in the array
}
if (diff.type == .removed) {
let docId = diff.document.documentID
//remove the message with this documentID from the array
}
self.lastDocumentSnapshot = snapshot!.documents.last
}
}
}
}
【问题讨论】:
-
欢迎来到 SO。请花时间格式化您的代码,使其易于阅读。您还有一个错字
.collectioncollection("messageRoom"),目前还不清楚哪条线路在 nil 上崩溃。此外,您不需要在 Firebase 函数闭包中使用DispatchQueue.main.async,因为 UI 调用在主线程上运行。最后,这个snapshot!是危险的,因为你不安全地打开一个可选项,如果它为 nil 就会崩溃(提示提示)。请通过安全地解包选项来保护您的代码和您的用户。 -
@Jay 我已经编辑了这个问题,之前的问题是通过添加“self.lastDocumentSnapshot = snapshot!.documents.last”来解决的,但是现在我无法在 func 中执行“else 查询”分页数据()”。感谢以上指导
-
我为您格式化了您的代码,使其易于阅读。请花点时间自己做这件事,因为疯狂的格式很难阅读,并且可能导致问题被关闭。
-
@Jay 感谢您的格式化,我会在以后处理这个问题,您能帮我把代码按要求准确吗
标签: ios swift firebase google-cloud-firestore pagination