如何解决尝试使用MKLocalSearch搜索并使用UISearchController显示结果
我是新手,我尝试创建用于列出要游览的地方的应用程序。我想使用MapKit在地图上进行搜索。我被this tutorial所吸引,即使年龄稍大。
这是我的视图控制器“ LocationSearchTable”
import MapKit
class LocationSearchTable : UITableViewController {
var matchingItems:[MKMapItem] = []
var mapView: MKMapView? = nil
func parseAddress(selectedItem:MKPlacemark) -> String {
// put a space between "4" and "Melrose Place"
let firstSpace = (selectedItem.subThoroughfare != nil && selectedItem.thoroughfare != nil) ? " " : ""
// put a comma between street and city/state
let comma = (selectedItem.subThoroughfare != nil || selectedItem.thoroughfare != nil) && (selectedItem.subAdministrativeArea != nil || selectedItem.administrativeArea != nil) ? "," : ""
// put a space between "Washington" and "DC"
let secondSpace = (selectedItem.subAdministrativeArea != nil && selectedItem.administrativeArea != nil) ? " " : ""
let addressLine = String(
format:"%@%@%@%@%@%@%@",// street number
selectedItem.subThoroughfare ?? "",firstSpace,// street name
selectedItem.thoroughfare ?? "",comma,// city
selectedItem.locality ?? "",secondSpace,// state
selectedItem.administrativeArea ?? ""
)
return addressLine
}
}
extension LocationSearchTable : UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
print("patate")
guard
let mapView = mapView,let searchBarText = searchController.searchBar.text else { return }
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = searchBarText
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start { response,_ in
guard let response = response else {
return
}
self.matchingItems = response.mapItems
print("++++ \(self.matchingItems.count) ++++")
self.tableView.reloadData()
}
}
}
extension LocationSearchTable {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
print("\(self.matchingItems.count) matchingitems")
return matchingItems.count
}
override func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
let selectedItem = matchingItems[indexPath.row].placemark
cell.textLabel?.text = selectedItem.name
cell.detailTextLabel?.text = parseAddress(selectedItem: selectedItem)
return cell
}
}
它与本教程中的几乎相同。我只是更新扩展中的功能,并插入一些“打印”来检查代码运行的部分。
当我运行该应用程序时,当我开始在搜索栏中输入任何字母时会发生错误。错误是“ UITableView数据源在索引路径:
我在堆栈溢出时发现了一些带有相同类型错误的消息,但是我无法修复自己的错误。 委托和数据源在情节提要中定义(使用表视图控制器时自动创建)。 matchingItems.countalways返回9或10,因此我对搜索有答案。 我认为展开单元格时会出现问题,而我找不到解决该问题的代码。
解决方法
我通过将Xcode中的Swift语言版本修改为5解决了这个问题。我不太了解发生了什么事情...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。