【问题标题】:filtering and displaying searchbar results from firebase database过滤和显示来自 firebase 数据库的搜索栏结果
【发布时间】:2017-02-25 17:43:23
【问题描述】:

我刚刚开始学习 swift 和 firebase。我想添加一个搜索栏,允许用户搜索我的 firebase 数据库。这就是我想要得到的 我添加了搜索栏,我遇到的问题是搜索结果的显示。 我创建了一个包含名称、子描述和徽标的容器视图,如上图所示,然后使用此函数进行设置

    func searchResultContainer(){
    searchResultView.addSubview(businesslogoView)
    searchResultView.addSubview(businessNameLabel)
    searchResultView.addSubview(businessSectorLabel)

    //need x. y, width, height constraints for searchResult
    searchResultView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    searchResultView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
    searchResultView.heightAnchor.constraint(equalToConstant: 220).isActive = true
}

然后我将 searchResult 视图附加到 var bussinesarray。然后将其插入到tableview中。请在下面查看我的代码

var businessArray = [NSDictionary]()
var filterBusiness = [NSDictionary]()

var ref : FIRDatabaseReference!

let searchController = UISearchController(searchResultsController: nil)

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.insertRows(at: [IndexPath(row: self.businessArray.count-1, section: 0)], with: UITableViewRowAnimation.automatic)
    ref.child("Businesses").queryOrdered(byChild: "Basic-Info/business").observe(.childAdded, with: { (snapshot) in

    view.addSubview(searchResultView)
    searchResultContainer()

    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    definesPresentationContext = true
    tableView.tableHeaderView = searchController.searchBar


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // if searchbar is not empty "", then return filtered businesses if the user is not typing anything return all businesses.
    if searchController.isActive && searchController.searchBar.text !=
        ""{
        return filterBusiness.count
    }
    return self.businessArray.count

}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    let business : NSDictionary?
    if searchController.isActive && searchController.searchBar.text !=
        ""{
        business = filterBusiness[indexPath.row]
    }
    else
    {
        business = self.businessArray[indexPath.row]
    }
    cell.textLabel?.text = business?["Business"] as? String
    cell.detailTextLabel?.text = business?["handle"] as? String

    return cell

}

func filterContent (searchText:String) {
    self.filterBusiness = self.businessArray.filter{ Businesses in
        let businessName = Businesses["Business"] as? String
        return(businessName?.contains(searchText.lowercased()))!
    }
    tableView.reloadData()

}

func updateSearchResults(for searchController: UISearchController) {

    // update the search results
    filterContent(searchText: self.searchController.searchBar.text!)
    }

我没有从 firebase DB 获取搜索结果,如何正确实现从 firebase DB 搜索结果?我正在以编程方式构建所有内容,请提供示例代码,不胜感激。

【问题讨论】:

  • 调用了filterContent?我认为您没有将请求发送到 fireBase DB,您只是在过滤您拥有的数组。
  • 如何将请求发送到 firebase DB
  • 看看文档,here's the link 看看 startAt()、endAt() 和 equalTo()

标签: ios swift search firebase-realtime-database uisearchbar


【解决方案1】:

本教程对我找出类似的实现有很大帮助,请参阅教程底部附近的代码。

http://shrikar.com/swift-ios-tutorial-uisearchbar-and-uisearchbardelegate/

本教程之外的代码调整包括以下代码。我仍然可以围绕 if/else 部分进行一些清理,但是对我来说两个关键概念是使用模型并通过以下方式正确获取目标:let temp: NSString = text.EntityName!作为 NSString

模型文件:

class Dealer: NSObject{

    var DealerNumber: String?
    var EntityName: String?
    //matchup all other firebase data fields
}

ViewController 调整

var dealerList = [Dealer]()
var filterDealers = [Dealer]()

---      

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    filterDealers = dealerList.filter({ (text) -> Bool in

        let temp: NSString = text.EntityName! as NSString
        let range = temp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
        return range.location != NSNotFound

    })

    if(filterDealers.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }
    refreshTable()
}

----

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cellIdentifier = "Cell"
    var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)

    cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier)

    if(searchActive){
        cell?.textLabel?.text = filterDealers[indexPath.row].EntityName
        cell?.detailTextLabel?.text = filterDealers[indexPath.row].DealerNumber

    } else {
        cell?.textLabel?.text = dealerList[indexPath.row].EntityName
        cell?.detailTextLabel?.text = dealerList[indexPath.row].DealerNumber
    }

    return cell!;
}

【讨论】:

    猜你喜欢
    • 2013-08-21
    • 2021-09-09
    • 2018-07-26
    • 1970-01-01
    • 2018-01-15
    • 2012-01-20
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    相关资源
    最近更新 更多