In the first part of this series of posts about Core Spotlight we looked at how to use the Core Spotlight APIs to index application data, how to search that data using Spotlight, and how to respond when a user selects a search result for your application’s data. In this post we’ll take a look at how easy it can be to search that same index from within your app. The demo app has been updated and is still available on GitHub.
Using CSSearchQuery to Search the Spotlight Index
In iOS 10 Apple introduced the CSSearchQuery class that allows us to search the same Spotlight index from within our app that we relied on in the first post when searching from the iOS Spotlight search field. The class is straightforward to use – you basically:
- Define the query using the straightforward search query syntax.
- Define handler blocks that are called when items are found or the search has completed.
- Start the search.
In the searchFor: method below, extracted from the AirportsViewController class of the demo app, you can see this process in action.
At the moment, it’s not possible to update an existing query so in the demo app as the user enters text into the search field we cancel any existing queries and create a new one with each change made to the search query. Despite that, if you’re taking advantage of Core Spotlight to index content within your app, the CSSearchQuery API makes it trivial to search that content, and is worth checking out in iOS 10.
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.