从MKLocalSearch更改为MKLocalSearchCompleter

时间:2018-11-14 21:11:28

标签: swift mapkit mklocalsearch mklocalsearchrequest

我已经按照教程设置了MKLocalSearchResponse,但是我不想在我的代码中使用MKLocalSearchCompleter。我发现了类似的问题here,但无法将其转换为代码。

我想要这样做是因为当客户搜索地址或类似地址时,我希望获得更多结果。

有人可以给我一些见解或提示来解决我的麻烦吗?这可能真的很简单,但是我尝试了没有成功。

class LocationSearchTable: UITableViewController {

weak var handleMapSearchDelegate: HandleMapSearch?
var matchingItems: [MKMapItem] = []
var mapView: MKMapView?
var localSearchResponse: MKLocalSearchResponse!

}

extension LocationSearchTable : UISearchResultsUpdating {

func updateSearchResults(for searchController: UISearchController) {
    guard let mapView = mapView,
        let searchBarText = searchController.searchBar.text else { return }



    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = searchBarText
    request.region = mapView.region
    let search = MKLocalSearch(request: request)

    search.start { localSearchResponse, _ in
        guard let response = localSearchResponse else {
            return
        }
        self.matchingItems = response.mapItems
        self.tableView.reloadData()
    }

}

}

extension LocationSearchTable {

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return matchingItems.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
    let selectedItem = matchingItems[(indexPath as NSIndexPath).row].placemark
    cell.textLabel?.text = selectedItem.name
    cell.detailTextLabel?.text = parseAddress(selectedItem)
    return cell
}

}

extension LocationSearchTable {

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selectedItem = matchingItems[(indexPath as NSIndexPath).row].placemark
    handleMapSearchDelegate?.dropPinZoomIn(selectedItem)
    dismiss(animated: true, completion: nil)
}

}

感谢您对我的帮助!

0 个答案:

没有答案