【发布时间】:2022-01-24 20:08:36
【问题描述】:
我正在快速开发一个应用程序,需要帮助。我试图在屏幕上显示一个搜索对象,当您键入字母时,它将使用 firebase 从实时数据库中获取结果。请帮忙。我不知道如何编码。请帮帮忙。
【问题讨论】:
标签: swift xcode firebase firebase-realtime-database search
我正在快速开发一个应用程序,需要帮助。我试图在屏幕上显示一个搜索对象,当您键入字母时,它将使用 firebase 从实时数据库中获取结果。请帮忙。我不知道如何编码。请帮帮忙。
【问题讨论】:
标签: swift xcode firebase firebase-realtime-database search
您必须更具体地了解您正在尝试做什么。首先 - 您使用什么技术? JavaScript?什么框架?反应?角? Vuejs?香草 JavaScript?你正在做的是一个安静的应用程序还是服务器渲染的?
根据您对上述问题的回答,代码可能会有很大差异。不过在这里我可以给你一个通用的解决方案:
【讨论】:
几周前我刚刚为我的应用程序做了这个,你很幸运!顺便说一句,我正在使用 swift 编程语言。
因此,根据 firebase,您不应该使用 firebase 在数据库中搜索文档。 Firebase Documentation on this.。相反,您应该使用其他东西,例如“Algolia”、“Elastic”或“typeSense”。我选择使用 Algolia,我花了大约一天时间来实现我的应用程序。超级简单。
但如果你真的想使用 firebase(不推荐),你可以使用这个:
func loadPost(lastDoc: QueryDocumentSnapshot?, completion: @escaping (QueryDocumentSnapshot?) -> Void) {
let db: Query
// Check to see if previous documents have been loaded or not.
if let lastDoc = lastDoc {
db = Firestore.firestore().collection("collection name")
.order(by: "document name you are wanting to get. example: postTitle, username, date, etc")
// Amount of documents you want to retrieve from your colleciton
.limit(to: 10)
// Check certain conditions that you want to retrieve.
// In this example we are only retrieving the posts that have 100 reports or greater.
.whereField("reportCount", isGreaterThan: 100)
// Start after the previous loaded document so we don't waste data by reloading documents that have already been loaded.
.start(afterDocument: lastDoc)
// If there are no previous loaded documents then you just start from the beginning of your collection colleciton.
} else {
db = Firestore.firestore().collection("posts")
.order(by: "document name", descending: true)
.limit(to: 10)
.whereField("document name", isGreaterThan: 100)
}
// finally get the documents you want from firebase
db.getDocuments { query, error in
// Check for errors
if let query = query, error == nil {
// Not really sure why you need a dispatchgroup, but its kind of like a completionHandler for a for loop.
let group = DispatchGroup()
for doc in query.documents {
group.enter()
// run the code you need to run:
// After the code is finished running you need to call group.leave()
group.leave()
}
// After the for loop is completely done call group.notify which is basically like a completionHandler
group.notify(queue: .main) {
// notify whatever needs to be notified.
// finally insert the last document loaded so when we need to load data again it only loads documents that have not been loaded.
completion(query.documents.last)
}
} else {
completion(nil)
}
}
}
【讨论】: