我正在尝试实现一个搜索栏,用户可以在其中输入字符串并搜索地址或企业。
为了寻找企业,我使用 Yelp API 来外包我需要的信息。
为了查找地址,我使用 Apple 的MKLocalSearch
API 来获取我需要的信息。
不过,我确实有问题。当我按住退格按钮从搜索栏中清除文本或在搜索栏中输入太快时,我收到MKErrorDomain
错误消息:
The operation couldn’t be completed. (MKErrorDomain error 3.)
当我收到此错误时,我将不得不等待片刻,以便代码再次运行并从 API 中检索信息。
以下代码是我必须实现我正在寻找的内容:
这是搜索栏委托方法:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == "" {
addServiceCellToTableView()
loadSearchHistory()
return
} else if searchBar.text != "" {
removeServiceCellFromTableView()
}
if searchCompleter.isSearching{
searchCompleter.cancel()
searchCompleter.region = (delegate?.businessSearchResultTableViewControllerNeedsUpdatedMapRegion(self))!
searchCompleter.queryFragment = searchText
} else {
searchCompleter.region = (delegate?.businessSearchResultTableViewControllerNeedsUpdatedMapRegion(self))!
searchCompleter.queryFragment = searchText
}
}
我用来MKLocalSearchCompleter
根据用户在搜索栏中输入的内容获取建议:
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter){
guard completer.results.count != 0 else {return}
var searchTerm: String = completer.results.first!.title
if completer.results.first!.subtitle != "" {
searchTerm = searchTerm + ", " + completer.results.first!.subtitle
}
if let _ = addressDetector.firstMatch(in: searchTerm, options: [], range: NSMakeRange(0, searchTerm.utf8.count)){
searchAddress(for: searchTerm)
} else {
getBusinesses(withSearchTerm: searchTerm, userCoordinates: currentUserLocation.coordinate)
}
}
在上面的代码中,我NSDataDetector
用来查看建议的文本是否是地址...如果是,我将其输入MKLocalSearch
...
最后,为了搜索地址,我定义了一个名为searchAddress(for:)
:
func searchAddress(for string: String){
let localSearchRequest = MKLocalSearchRequest()
localSearchRequest.naturalLanguageQuery = string
localSearchRequest.region = (delegate?.businessSearchResultTableViewControllerNeedsUpdatedMapRegion(self))!
let localSearch = MKLocalSearch(request: localSearchRequest)
localSearch.start(completionHandler: {searchResponse, error in
guard error == nil else {
print(error.debugDescription)
return
}
guard let mapItems = searchResponse?.mapItems else {return}
self.tableViewDataSourceList = mapItems
self.tableView.reloadData()
self.delegate?.businessSearchResultTableViewStopedGettingBusiness(self, with: self.tableViewDataSourceList, at: CLLocationCoordinate2D(latitude: self.currentUserLocation.coordinate.latitude, longitude: self.currentUserLocation.coordinate.longitude))
})
}
当我键入太快或按住退格键时,我在控制台中收到以下错误:
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
任何帮助都感激不尽 :-)