我想在我的应用程序中实现搜索功能。我希望当用户在搜索栏中搜索特定商店时,它将搜索firestore数据库并用他输入的特定商店填充tableview。
但是我被困在searchBar函数中以及如何查询firestore来检索和存储用户在搜索栏中输入的文本。
到目前为止,这是我的代码:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredShops = []
db.collection("Shops").whereField("name", isLessThanOrEqualTo: searchText).addSnapshotListener{ (query, error) in
if error != nil {return}
guard let doucments = query?.documents else {return}
for doc in doucments {
self.sName = doc["name"] as? String
self.sLoc = doc["location"] as? String
self.sImg = doc["ShopHeaderImg"] as? String
self.filteredShops.append(self.sName!)
self.filteredShops.append(self.sLoc!)
self.filteredShops.append(self.sImg!)
}
}
print("is typing")
}
}
extension SearchTableViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredShops.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = searchTV.dequeueReusableCell(withIdentifier: "searchShop")! as UITableViewCell
cell.textLabel?.text = filteredShops[0]
return cell
}
}
如何使用Firestore数据库实现此功能?
好,这里是一些伪代码
为自己创建更易于使用的东西,以作为数据模型
struct Shop {
let name: String?
let location: String?
let image: String?
init(from document: Document) {
name = document["name"] as? String
location = document["location"] as? String
image = document["ShopHeaderImg"] as? String
}
}
然后在您的视图控制器中添加数据源
var shops: [Shop] = []
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
db.collection("Shops")
.whereField("name", contains: searchText)
.addSnapshotListener { [weak self] (query, error) in
// make sure you capture self weak as it may lead to memory leak
guard let self = self, let documents = query?.documents else { return }
// simply transform your Documents to Shops and update your dataSource
self.shops = documents.map { Shop(from: $0) }
// Reload your table view and show the result
self.tableView.reloadData()
}
}
}
extension SearchTableViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return shops.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = searchTV.dequeueReusableCell(withIdentifier: "searchShop")! as UITableViewCell
let shop = shops[indexPath.row]
cell.textLabel?.text = shop.name
return cell
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句