运行此代码时出现“致命错误:在解包可选值时意外发现nil”的错误:
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
// Request Google maps API, all returned places should be assigned to the array that works as the table view data source
let placesClient = GMSPlacesClient()
placesClient.autocompleteQuery(searchText, bounds: nil, filter: nil) { (results, error:NSError?) -> Void 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.searchResultController.reloadDataWithArray(self.resultsArray)
}}
有谁知道为什么?
答案 0 :(得分:1)
所以我自己实现了它,它就像一个魅力:
/// Search for the cities after every change in SearchBar - uses google maps SDK and autocomplete.
///
/// - parameter searchBar: current SearchBar
/// - parameter searchText: entered text we want to use for search
func searchBar(searchBar: UISearchBar, textDidChange searchText: String){
let placesClient = GMSPlacesClient()
placesClient.autocompleteQuery(searchText, bounds: nil, filter: nil) { (results, error:NSError?) -> Void in
self.cities.removeAll()
if let theResults = results {
for result in theResults {
if let result = result as? GMSAutocompletePrediction{
self.cities.append(result.attributedFullText.string)
}
}
dispatch_async(dispatch_get_main_queue(), {
self.tableView.hidden = false
self.tableView.reloadData()
})
} else {
// It is necessary to reload data everytime. given scenario: clear whole text and theResults is nil but there preserve data in table which can lead to exception
dispatch_async(dispatch_get_main_queue(), {
self.tableView.hidden = false
self.tableView.reloadData()
})
}
}
}
恐怕我现在无法提供更多帮助:/