Ty Daniels Ty Daniels - 7 months ago 257
Swift Question

Attempting to replicate GMSPlacesClient: autoCompleteQuery function to populate a UITableView manually

My current code to populate a tableView with addresses from the Google Places API endpoint is as follows:

However, I want to create a custom client to handle the functionality that autoCompleteQuery, provided by Places, takes care of but manually. I'm assuming this calls for the address JSON to be parsed again, and iterated through, then stored in an array. Please let me know if you have a solution. The commented code works perfectly, I'm trying to achieve the same result manually.

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

// let mapsClient = GMSPlacesClient()
// mapsClient.autocompleteQuery(searchText, bounds: nil, filter: nil {(results, error: NSError?) in
//
// self.resultsArray.removeAll()
//
// if results == nil{
// return
// }
//
// for result in results! {
//
// if let result = result as GMSAutocompletePrediction! {
// self.resultsArray.append(result.attributedFullText.string)
// }
// }
//
// self.searchResultsClient.reloadDataWithArray(self.resultsArray)
// }

gmsFetcher?.sourceTextHasChanged(searchText)

self.searchResultsClient.reloadDataWithArray(self.resultsArray)
print(resultsArray)
}


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

extension MainMapViewController: GMSAutocompleteFetcherDelegate {
func didAutocompleteWithPredictions(predictions: [GMSAutocompletePrediction]) {

self.resultsArray.count + 1

let resultsStr = NSMutableString()
for prediction in predictions {
resultsStr.appendFormat("%@\n", prediction.attributedPrimaryText)
}

resultText?.text = resultsStr as String
self.resultsArray.append(resultsStr as String)
self.searchResultsClient.reloadDataWithArray(self.resultsArray)
}
func didFailAutocompleteWithError(error: NSError) {
resultText?.text = error.localizedDescription
}
}

Answer

You can use GMSAutocompleteFetcher, which wraps the autocompleteQuery method on GMSPlacesClient. The fetcher throttles requests, returning only results for the most recently entered search text and provides no UI elements.

Steps to implement GMSAutocompleteFetcher:

  1. Implement the GMSAutocompleteFetcherDelegate protocol.
  2. Create a GMSAutocompleteFetcher object.
  3. Call sourceTextHasChanged on the fetcher as the user types.
  4. Handle predictions and errors using the didAutcompleteWithPredictions and didFailAutocompleteWithError protocol methods.

Sample code demonstrating the implementation steps in using the fetcher can be found in Use the fetcher.