0

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

pkamb
  • 33,281
  • 23
  • 160
  • 191
TrevPennington
  • 435
  • 5
  • 15

1 Answers1

1

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()
    }
}
pkamb
  • 33,281
  • 23
  • 160
  • 191
Kstin
  • 659
  • 1
  • 4
  • 18
  • ok thank you, it seems to no longer crash but after the 3rd or 4th attempt at searching - the table view results do not change and I get: searchText Rale Error: The operation couldn’t be completed. (MKErrorDomain error 3.). in the console. Also, I'll accept your answer as correct if my issue is different now. Change the let newArray to var by the way, thanks Kstin! – TrevPennington Sep 03 '20 at 13:35