从firebase数据库过滤和显示搜索栏结果

时间:2017-02-25 17:43:24

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

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

    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的搜索结果?我正在以编程方式构建所有内容,请非常感谢示例代码。

1 个答案:

答案 0 :(得分:1)

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

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

本教程之外的代码调整包括以下代码。我仍然可以围绕if / else部分进行一些清理,但是我的两个关键概念是使用模型并使目标正确:让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!;
}