实现自定义搜索栏,使用文本字段作为输入来搜索文本以及如何在iOS Swift中调用Search api

时间:2019-06-21 10:50:08

标签: ios swift search uitextfield uisearchbar

我已经使用文本字段搜索文本,并且可以很好地处理虚拟硬编码数据。不知道如何从API解析搜索数据。我的json文件链接为:https://api.myjson.com/bins/x8a4x,其中包含搜索的主体参数。我错了,请纠正我。并已在文本字段下方使用tableview来显示搜索数据

我的搜索页面控制器文件:-

class SearchPageController: UIViewController {

    @IBOutlet weak var searchTxtBar: UITextField!
    @IBOutlet weak var searchTblView: UITableView!

    @IBOutlet weak var searchMessage: UIView!

    var CatStoreData:[String] = Array()
    var filteredData:[String] = Array()

    var searchData = [ModelSearched]()

    var search = "M"

    override func viewDidLoad() {
        super.viewDidLoad()

        self.hideKeyboardWhenTappedAround()
        self.searchMessage.isHidden = true

        // Do any additional setup after loading the view.
        searchTxtBar.delegate = self

        //append data to catstoredata array
        CatStoreData.append("costco.com.au")
        CatStoreData.append("au.kogan.com")
        CatStoreData.append("rebelsport.com.au")
        CatStoreData.append("ebgames.com.au")
        CatStoreData.append("computeralliance.com.au")
        CatStoreData.append("harveynorman-com-au")
        CatStoreData.append("binglee.com.au")
        CatStoreData.append("iwantthatflight.com.au")
        CatStoreData.append("mobileciti.com.au")
        CatStoreData.append("Electronics and Gadgets")
        CatStoreData.append("Baby Care")
        CatStoreData.append("Computers")
        CatStoreData.append("Computers and Laptops")
        CatStoreData.append("Entertainment")
        CatStoreData.append("Eyewear")
        CatStoreData.append("Flights")
        CatStoreData.append("Home & Kitchen")

        for data in CatStoreData {
            filteredData.append(data)
        }
        searchTxtBar.addTarget(self, action: #selector(searchRecords(_ :)), for: .editingChanged)
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

    @objc func searchRecords(_ textfield: UITextField) {

//        self.CatStoreData.removeAll()
        self.CatStoreData.removeAll()
        if searchTxtBar.text?.count != 0 {
            for data in filteredData {

                if let dataToSearch = self.searchTxtBar.text {
                    let range = data.lowercased().range(of: dataToSearch, options: .caseInsensitive, range: nil, locale: nil)
                    if range != nil {
                        CatStoreData.append(data)
                    }
                }
            }
        }else {
            for data in filteredData {
                CatStoreData.append(data)
            }
        }

        searchTblView.reloadData()
    }

    //MARK: IBActions
    @IBAction func toHomeScreen(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }

    func getSearchList(search: String){

        if ApiUtillity.sharedInstance.isReachable()
        {
            ApiUtillity.sharedInstance.StartProgress(view: self.view)
            APIClient<ModelBaseSearchList>().API_GET(Url: SD_GET_SearchList+"\(search)", Params: [:], Authentication: true, Progress: true, Alert: true, Offline: false, SuperVC: self, completionSuccess: { (modelResponse) in

                ApiUtillity.sharedInstance.StopProgress(view: self.view)

                if(modelResponse.success == true) {

                    self.searchData.removeAll()
                    let resul_array_tmp_new = modelResponse.searched as! NSArray

                    if resul_array_tmp_new.count > 0 {
                        for i in modelResponse.searched! {
                            self.searchData.append(i)
                        }
                    }
                }
                else {
                    self.view.makeToast(modelResponse.message)
                }
                ApiUtillity.sharedInstance.StopProgress(view: self.view)
                self.searchTblView.reloadData()
            }) { (failed) in
                ApiUtillity.sharedInstance.StopProgress(view: self.view)
                self.view.makeToast(failed.localizedDescription)
            }
        }
        else
        {
            self.view.makeToast("No Internet Connection..")
        }
    }

    @IBAction func clearSearchData(_ sender: UIButton) {

        self.CatStoreData.removeAll()
        self.searchTxtBar.text = ""
        for data in filteredData {
            CatStoreData.append(data)
        }
        searchTblView.reloadData()
    }

}

//MARK: Tableview delegates and datasource methods
extension SearchPageController: UITableViewDelegate, UITableViewDataSource{

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

       return searchData.count
    }

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

        var cell = tableView.dequeueReusableCell(withIdentifier: "catstoredata")

        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "catstoredata")
        }

        cell?.selectionStyle = .none
        cell?.textLabel?.text = CatStoreData[indexPath.row]
        return cell!
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        self.navigationController?.popViewController(animated: true)
    }
}

//MARK: textfield delegates method
extension SearchPageController: UITextFieldDelegate{

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        self.searchTxtBar.resignFirstResponder()
        return true
    }

}

0 个答案:

没有答案