How to Write Async Search Bar Controller

July 11, 2019

How do you handle the search if you are searching among millions of records?

What happens when a user enters some text to search and realised that he wanted to search something else or mistyped something?

Ideally, when a user changes the text we should stop our search and begin a search with the new text entered by a user.

How should we write such a code in swift to make sure we cancel the search before starting a new search?

Operation Queue is a good way to handle these kinds of situations. So, let’s get our hands dirty to write a piece of code for it.

We need a delegate which provides a set of APIs to use search functionality as below:

We just wrote a SearchControllerDelegate protocol which has properties and methods as:


  • searchQueue to perform Async search task.
  • searchResult stores results returned from the search.


  • searchDisplayController(controller:SearchViewController, searchText:String) to start a search with the searchText
  • cancelSearch() to cancel the search

Here, how do we use delegate protocol in our ViewController:

How to connect SearchControllerDelegate to UI:

A simple example of the Async search can be found here.

Originally published at Medium

Fission Labs uses cookies to improve functionality, performance and effectiveness of our communications. By continuing to use this site, or by clicking “I agree” you consent to the use of cookies. Detailed information on the use of cookies is provided on our Cookies Policy