iOS MKLocalSearch causing crash

134 views Asked by At

I am performing MKLocalSearch with a UISearchBar and a UITableView.

The first search always works great but if you try another one, the app crashes and I get an "index out of range error". Let me know if you need more info, thanks.

    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)
    }
}

After the 3rd or 4th attempt at searching, the results in the table stays the same and no more results are logged. I get the error:

Error: The operation couldn’t be completed. (MKErrorDomain error 3.)

1

There are 1 answers

1
Kstin On

Your problem was that you changed searchResults too early. Try:

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()
    }
}