How to have a searchbar which shows suggestions wi

2019-07-14 17:04发布

问题:

I want to have a search bar at navigation bar and when the user start typing, show some suggestions, but in additional the uitableview has to be different than the results of search. For example: User starts typing 'wh': then shows a list with white, wheater, who, ... And then when press search button shows other list with the results.

In this case the complication goes on uitableviewcell, because they are different cells with different fields.

回答1:

I saw your question while i was looking for the same thing. Now i have learned how to show google suggestions and autocomplete in different tableview. I am sure you have already accomplished it but i will answer anyway in case someone else needs it.

First you need to insert tableview to view like this when searchBar textfield editingDidBegin method get called:

    func showSuggestionsTableView() {
        if suggestionsTableView == nil {
            //I get keyboardhight dynamically and 60 is my navigationBar height.
            let availHeight = Globals.deviceScreenSize!.size.height - 60 - CGFloat(keyboardHeight)
            suggestionsTableView = UITableView(frame: CGRect(x: 0, y: 82, width: Globals.deviceScreenSize!.size.width, height: availHeight), style: .grouped)
            suggestionsTableView?.delegate = self
            suggestionsTableView?.dataSource = self

            self.view.insertSubview(suggestionsTableView!, aboveSubview: webViewContainer)
        suggestionsTableView?.isHidden = false
    }

How i remove tableview from view when user is done with search

  func removeSuggestionsTableView() {
        suggestionsTableView?.removeFromSuperview()
        suggestionsTableView = nil
    }

Than i created suggestions manager to get suggestion and autocomplete data. Create protocol to communicate with other classes: Than create your manager class, don't forget to call XMLParserDelegate. You have to parse XML data coming from google.

protocol GoogleAutoComplateManagerDelegate {
    func didDownloadResults(resultArr: [String]?)
    func didFail(String)
}

class GoogleAutoComplateManager : NSObject, XMLParserDelegate {

var delegate : GoogleAutoComplateManagerDelegate?
static let sharedInstance = GoogleAutoComplateManager()

var parser = XMLParser()
var resultArr = [String]()



func getAutoComplateResults(stringToSearch: String) {
    if stringToSearch != "" {
        resultArr = []
        //You can find about this google url parameters online. For now 'hl' is language parameter.
        let googleURL = "http://suggestqueries.google.com/complete/search?output=toolbar&hl=tr&ie=utf8&oe=utf8&q="
        let searchURL = URL(string: googleURL + stringToSearch.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!)

        parser = XMLParser(contentsOf: searchURL!)!
        self.parser.delegate = self

        let success:Bool = self.parser.parse()

        if success {
            delegate?.didDownloadResults(resultArr: resultArr)
        }
        else {
            delegate?.didFail("parser error")
        }

    }
}


func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
    //This delegate method loops through every suggestion in xml file and parses it
    if (elementName == "suggestion") {
        let suggestion : String = attributeDict["data"]!
        resultArr.append(suggestion)
    }


 }

    func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
        //Parser delegate method for error handling while parsing
        delegate?.didFail(parseError.localizedDescription)
    }

}

Now you can call your class from anywhere like this;

GoogleAutoComplateManager.sharedInstance.delegate = self
GoogleAutoComplateManager.sharedInstance.getAutoComplateResults(stringToSearch: yourSearchString)

Don't forget to implement delegate methods.

Hope it helps someone.

Cheers.