MapKit local search results populate the table

181 Views Asked by At

I am trying to load the updated search results but it doesn't populate the table view.

I used this link https://www.thorntech.com/how-to-search-for-location-using-apples-mapkit/ which belongs to the previous versions but it still works very well except showing the local search results.

class LocationSearchTable : UITableViewController, UISearchResultsUpdating {
    var matchingItems:[MKMapItem] = []
    var mapView: MKMapView? = nil
    
}

extension LocationSearchTable {
    func updateSearchResults(for searchController: UISearchController) {
        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 {
                print("No response")
                return
            }
            self.matchingItems = response.mapItems
            self.tableView.reloadData()
        }
    }
}

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

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

There are 1 best solutions below

0
ho jasper On
 //use IndexPath rather than NSIndexPath and you need to use 
 //override

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

Hope it is not too late to answer you!