NEW: Master Swift design patterns with my latest book! >>

How to search your app’s Spotlight index

Written by Paul Hudson    @twostraws

If you choose to index your app’s content using Spotlight (and you should), you can then use more Core Spotlight code to search your own index from inside your app.

All the work is done using the CSSearchQuery class, which works asynchronously. You need to give it two closures to work with: one to call when it finds a matching item (which should append the item to a results array), and one to call when the search finishes, at which point you should update your UI with the search results.

CSSearchQuery works similarly to Core Data – it even has the same approach to specifying search criteria. In this example we’re going to search for "contentDescription == \"*\(text)*\"c", which means “find things that have a contentDescription value equal to any text, followed by our search text, then any text, using case-insensitive matching.

There are a few more things you need to know before I show you the code:

  1. Running a CSSearchQuery returns CSSearchableItem items, so we need to an array to store that data type.
  2. We’ll be taking advantage of closure capturing to share that array between the “found items” closure and the “search is finished” handler.
  3. Your closures can be called on any thread, so as you usually manipulate the UI when the search finishes you should push that work to the main thread.
  4. You need to explicitly call start() on the search to make it begin.
  5. In case a user types really fast, we want to a way to cancel the existing search before starting a new one. To make that happen, it’s a good idea to store the CSSearchQuery object as a property in the class, then call cancel() on it before searching.

To try out the code below, add import CoreSpotlight to a view controller’s class, then give it a CSSearchQuery? property called searchQuery.

Now add this method:

func runSearch(text: String) {
    var allItems = [CSSearchableItem]()

    searchQuery?.cancel()

    let queryString = "contentDescription == \"*\(text)*\"c"
    searchQuery = CSSearchQuery(queryString: queryString, attributes: nil)

    searchQuery?.foundItemsHandler = { items in
        allItems.append(contentsOf: items)
    }

    searchQuery?.completionHandler = { error in
        DispatchQueue.main.async { [unowned self] in
            self.updateUI(matches: allItems)
        }
    }

    searchQuery?.start()
}

You’ll need to implement updateUI() to do something with your search results, such as updating a table view.

Available from iOS 10.0 – learn more in my book Advanced iOS: Volume One

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Take Swift further!

Your Swift skills let you make apps for macOS, watchOS, tvOS, and more, and for one low price you can learn it all with my Swift Platform Pack!

Click here to visit the Hacking with Swift store >>