Drop me an email if you'd like to hire me (part time) or learn more about what I do. You can read about my experience and references on LinkedIn.
iOS: Searching with UISearchController
iOS 8 brought a lot of new APIs for developers. One of them is new API used for searching. Before iOS 8 we’re using UISearchDisplayController. Since iOS 8
there is new UISearchController available - let’s play
with it for a moment and implement in Quotes app.
The new API requires to implement UISearchBarDelegate for dealing with
UISearchBar, UISearchControllerDelegate for the new search controller
(all of them are optionals) to react when search controller will/did present
or dismiss and finally UISearchResultsUpdating protocol which has method
that is called when search bar text changes or when search bar becomes first
Before iOS 8 it was possible to drag and drop “Search Bar and Search Display Controller” on a table view and the controller was ready to use, except writing filtering and telling when to search. Unfortunately, or fortunately
(I like this new one) this property has been deprecated and probably will be
obsolete in iOS 10.
In the past I dealt with UISearchDisplayController and used the same UITableViewDelegate and UITableViewDataSource protocols implementation for
search controller and main table view from the class where table view was
contained. There was also code responsible for entries filtering. The code was
in one view controller and was very messy. I didn’t work out better solution or
flow - I think there are few. Using UISearchController code can be easily
decoupled and easy to maintain.
The first thing to think about is what will be displayed in main table view and
what in filtered one. Let’s assume that in Quote app we want to display quotes
in both main and filtered table. So the same cell can be used. Let’s detach it
to separated xib and create the class.
Cells and table views are the same. The good practice is to share common code
to avoid repeating. Let’s create QuoteListBaseTableViewController which holds
base informations about table view and cells - this class will be also used as a
search results controller. And QuoteListViewController class - it inherits
from the base, contains search bar and main table with quotes.
Okay. Now is the time to create search controller, results table controller and
results updater which is responsible for filtering content.
And here search controller is configured:
I kept entire implementation in view controller with main table view and realized
it was not necessary and finally detached results updater to separated file to
keep view controller as clean and simple as possible.
Implementation of results updater is easy. There is only one protocol and one
method to implement. Method is called when text changes in search bar. It is
responsible for parsing search text and creating predicates for filtering.
At the end it changes content of search results controller and calls reloadData() on its table view.