0

I have a Search Bar with a UITableView and if I search something in the searchBar it will print the result in the table view.

If I search a name like "Name 01" and I click on this name to get information and later I re-open the Search Bar and I try to search other name like "Name 02" I will see the "Name 01" result in the Table View and I don't know how to clear it.

I have tried to refresh Table View too but without success.

Video of the problem: https://streamable.com/98j0w

The code is this

extension LocationSearchTable : UISearchResultsUpdating {
    func updateSearchResults(for searchController: UISearchController) {
        //print("updateSearchResults")

        if searchController.searchBar.text == nil {
            seenNames.removeAll()
            matchingItems.removeAll()
            self.tableView.reloadData()
        }

        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 { response, _ in
            guard let response = response else {
                return
            }

            for (index , name) in response.mapItems.enumerated() {
                let item = response.mapItems[index]
                if(checkIfItemExistInDatabase(key: String(item.name!)) != nil && !seenNames.contains(name.name!)){
                    matchingItems.append(item)
                    seenNames.insert(name.name!)
                    self.tableView.reloadData()
                }
            }
        }
    }
}

I want that If I do a research the tableview result with searchbar text is cleaned and doesn’t show the previously result

Francesco Deliro
  • 3,899
  • 2
  • 19
  • 24

1 Answers1

0

Instead of:

if searchController.searchBar.text == nil {
...
...

Try with

let searchText = searchController.searchBar.text
if searchText == nil || searchText.isEmpty { 
...
...

And another thing, just before

search.start { response, _ in

add

matchingItems.removeAll()
tableView.reloadData()
iGenio
  • 398
  • 1
  • 8
  • Yes but I don’t need that. I need that if I do a research the tableview is clean and doesn’t show the previously result –  Jun 12 '18 at 13:10
  • i know, that's the goal of the proposed solution – iGenio Jun 12 '18 at 13:14
  • If you put removeAll before search when the text change (when I am trying to put the full name) it will clear always the result. We can’t put that –  Jun 12 '18 at 13:46