Search code examples
iosarraysuisearchbaruisearchcontrollerlivesearch

How to convert searchController to a live search


I have a searchController which does the searching really good and populates the right values. But these codes returns value if the searchingText and the values. I need search bar to make the search live. For example when i put 40027, this function has to return every value which starts with 40027(for instance 40027-60)

Here is my search function:

    func updateSearchResults(for searchController: UISearchController) {
    if searchController.isActive {
        filteredData.removeAll(keepingCapacity: false)
        let textToSearch = searchController.searchBar.text!
        filteredData = feedItems.filter({$0.DesenNo?.caseInsensitiveCompare(textToSearch) == .orderedSame})
        listTableView.reloadData()
    }
    else {
        filteredData.removeAll(keepingCapacity: false)
        listTableView.reloadData()
    }
}

Solution

  • Rather than looking for the exact string, what you can do is use the contains method on the string to compare.

    Complete apple documentation can be found here: https://developer.apple.com/documentation/foundation/nsstring/1414563-containsstring

    Edited: Your compare may look like this

    filteredData = feedItems.filter({$0.DesenNo?. lowercaseString.contains(textToSearch.lowercaseString)})