我当前使用Google Places API端点的地址填充表视图的代码如下:
但是,我想创建一个自定义客户端来处理Places提供的autoCompleteQuery手动处理的功能。我假设这需要再次解析地址JSON,并进行迭代,然后存储在数组中。如果你有解决方案,请告诉我。注释的代码运行得很好,我正在尝试手动实现相同的结果。
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
}
}
您可以使用GMSAutocompleteFetcher
,它将autocompleteQuery方法封装在GMSPlacesClient
上。fetcher抑制请求,只返回最近输入的搜索文本的结果,不提供UI元素。
实现GMSAutocompleteFetcher:的步骤
- 实现
GMSAutocompleteFetcherDelegate
协议- 创建一个
GMSAutocompleteFetcher
对象- 当用户键入时,在提取器上调用
sourceTextHasChanged
- 使用
didAutcompleteWithPredictions
和didFailAutocompleteWithError
协议方法处理预测和错误
演示使用提取器的实现步骤的示例代码可以在使用提取器中找到。
解决:以下是我如何最终解决在从UISearchBar更新文本时使用自动完成功能更新UITableView行的问题。
func searchBar(searchBar: UISearchBar, textDidChange searchText: String){
self.resultsArray.removeAll()
gmsFetcher?.sourceTextHasChanged(searchText)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//Implement GMSAutoCompleteFetcherDelegate protocol to handle custom string prediction
extension MainMapViewController: GMSAutocompleteFetcherDelegate {
func didAutocompleteWithPredictions(predictions: [GMSAutocompletePrediction]) {
for prediction in predictions {
if let prediction = prediction as GMSAutocompletePrediction!{
self.resultsArray.append(prediction.attributedFullText.string)
}
}
self.searchResultsTable.reloadDataWithArray(self.resultsArray)
print(resultsArray)
}
func didFailAutocompleteWithError(error: NSError) {
resultText?.text = error.localizedDescription
}
}