如何在表格视图中实现UISearchBar从firestore的搜索



我想在我的应用程序中实现搜索功能。我希望当用户在搜索栏中搜索特定商店时,它会搜索消防商店数据库,并用他输入的特定商店填充表视图。

但我被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
}
}

最新更新