我使用UISearchBar和UITableView执行MKLocalSearch。
第一次搜索总是很有效,但如果你尝试另一次,应用程序会崩溃,我会得到一个";索引超出范围误差";。如果你需要更多信息,请告诉我,谢谢。
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
self.searchResults = [] //this might be causing the crash
print("searchText (searchText)")
let searchRequest = MKLocalSearch.Request()
searchRequest.naturalLanguageQuery = searchText
let search = MKLocalSearch(request: searchRequest)
search.start { response, error in
guard let response = response else {
print("Error: (error?.localizedDescription ?? "Unknown error").")
return
}
for item in response.mapItems {
self.searchResults.append(item.placemark)
self.tableView.reloadData()
}
}
}
}
//MARK: TableView
extension LocationSearchViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchResults.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ResultCell", for: indexPath)
let listItem = searchResults[indexPath.row]
cell.textLabel?.text = listItem.name
cell.detailTextLabel?.text = listItem.administrativeArea ?? ""
return cell
}
}
extension LocationSearchViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("selected a row")
let local = searchResults[indexPath.row]
// pass local back
if let delegate = delegate{
delegate.doSomethingWith(data: local)
}
dismiss(animated: true, completion: nil)
}
}
第三次或第四次尝试搜索后,表中的结果保持不变,不再记录更多结果。我得到错误:
错误:操作无法完成。(MKErrorDomain错误3.(
您的问题是过早更改了searchResults。尝试:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
print("searchText (searchText)")
let searchRequest = MKLocalSearch.Request()
searchRequest.naturalLanguageQuery = searchText
let search = MKLocalSearch(request: searchRequest)
search.start { response, error in
guard let response = response else {
print("Error: (error?.localizedDescription ?? "Unknown error").")
return
}
var newArray: [YourStruct] = []
for item in response.mapItems {
newArray.append(item.placemark)
}
self.searchResults = newArray
self.tableView.reloadData()
}
}