自动填充

时间:2016-02-24 07:06:45

标签: ios swift uisearchcontroller

我正在快速构建一个应用程序,需要能够搜索城市,我希望搜索能够自动完成。我想做一些事情,比如如果用户在搜索框中键入任何字符或单词,它会从mysql数据库中获取从该字符或单词开始的结果,并在自动建议或自动完成中显示结果。我的后端服务准备就绪..唯一的问题是我不知道如何实现这个功能。目前我的代码正在做的是当用户在搜索栏中输入内容时,他点击键盘中的搜索按钮,然后结果出现。希望你能理解我在说什么。这是我目前的代码

class ViewController: UIViewController, UITableViewDataSource, UISearchBarDelegate {
    @IBOutlet weak var mySearchBar: UISearchBar!
    @IBOutlet weak var myTableView: UITableView!
   var dict = NSDictionary()
    var searchResults = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    }

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

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return searchResults.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
       let myCell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) 

        myCell.textLabel?.text = searchResults[indexPath.row]

        return myCell

    }

    func searchBarSearchButtonClicked(searchBar: UISearchBar)
    {
         if(searchBar.text!.isEmpty)
         {
            return
         }

        doSearch(searchBar.text!)

    }



    func doSearch(searchWord: String)

    {

      mySearchBar.resignFirstResponder()

        let myUrl = NSURL(string: "http://localhost/myproject")
         let request = NSMutableURLRequest(URL:myUrl!);

        let params = ["city" : searchWord]
        do {

            let data = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)



            request.HTTPBody = data


        } catch {
            //handle error. Probably return or mark function as throws
            print("error is \(error)")
            //return
        }


        request.HTTPMethod = "POST";



        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response: NSURLResponse?, error:NSError?) -> Void in

            dispatch_async(dispatch_get_main_queue()) {

            if error != nil
            {
                // display an alert message
                self.displayAlertMessage(error!.localizedDescription)
                return
            }
              let json: NSDictionary?
         do {
            json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

            self.searchResults.removeAll(keepCapacity: false)
            self.myTableView.reloadData()

            if let parseJSON = json {
              print(parseJSON)

               // var index = 0
                self.dict = parseJSON
              print("count is \(self.dict.count)")
                for var i = 0; i < self.dict.count - 1; i++ {
                    let cityname = (((self.dict["\(i)"] as?NSDictionary)!["City"] as?NSDictionary)!["name"] as?NSString)! as String
                   self.searchResults.append(cityname)
                }



                        self.myTableView.reloadData()


            }

            } catch {
                print(error);
            }

            }


            })


        task.resume()

    }


    func displayAlertMessage(userMessage: String)
    {
        let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert);
        let okAction =  UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
        myAlert.addAction(okAction);
        self.presentViewController(myAlert, animated: true, completion: nil)
    }

    @IBAction func cancelButtonTapped(sender: AnyObject) {
        mySearchBar.text = ""
        mySearchBar.resignFirstResponder()
    }




}

2 个答案:

答案 0 :(得分:0)

这是一种技巧:

  • 使您的ViewController成为搜索栏文本字段的委托。
  • 实施委托 -

  • 搜索栏:textDidChange:

  • 实施方法说&#39; UpdateResults&#39;这种方法应该这样做 -

    一个。检查searchBar是否已更改,在这种情况下设置searchResults 为nil(创建一个实例var searchResults,它是可选的数组。

    湾执行网络操作以异步方式获取结果(如 你已经这样做了。)

    ℃。收到结果后,将它们附加到searchResults(by 创造它,如果它是零)

    d。一旦附加了所有搜索结果,就在主线程上调度,然后 使相关结果表重新加载。

答案 1 :(得分:0)

好吧我已经成功实现了搜索。这是我的代码

class  CityTableViewController: UITableViewController, UISearchResultsUpdating {
    var dict = NSDictionary()
    var filterTableData = [String]()
    var resultSearchController = UISearchController()


    var newTableData = [String]()


    override func viewDidLoad() {
        super.viewDidLoad()



        self.resultSearchController = ({

            let controller  = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.dimsBackgroundDuringPresentation = false
            controller.searchBar.sizeToFit()
            self.tableView.tableHeaderView = controller.searchBar
            return controller


        })()

        self.tableView.reloadData()
    }

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


        if(self.resultSearchController.active){

            return self.filterTableData.count
        }else {

            return dict.count
        }



    }



    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CountryTableViewCell

        if(self.resultSearchController.active){

            cell.cityNameLabel.text = filterTableData[indexPath.row]
            return cell

        }else{

            cell.cityNameLabel.text = (((self.dict["\(indexPath.row)"] as?NSDictionary)!["City"] as?NSDictionary)!["name"] as?NSString)! as String
            return cell
        }



    }

    func updateSearchResultsForSearchController(searchController: UISearchController) {
        filterTableData.removeAll(keepCapacity: false)
        let searchWord = searchController.searchBar.text!

        getCityNamesFromServer(searchWord)

        let searchPredict = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
        print("searchPredict is \(searchController.searchBar.text!)")

        for var i = 0; i < self.dict.count; i++ {
            let cityname = (((self.dict["\(i)"] as?NSDictionary)!["City"] as?NSDictionary)!["name"] as?NSString)! as String
        newTableData.append(cityname)
        }

        let array = (newTableData as NSArray).filteredArrayUsingPredicate(searchPredict)
        print("array is\(array)")
        filterTableData = array as! [String]
        self.tableView.reloadData()
    }






    func getCityNamesFromServer(searchWord:String){


        let url:String = "http://localhost/"
        let params = ["city":searchWord]



        ServerRequest.postToServer(url, params: params) { result, error in

            if let result = result {
                print(result)

                self.dict = result

            }
        }

    }

}