Swift version: 5.10
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:
CSSearchQuery
returns CSSearchableItem
items, so we need to an array to store that data type.start()
on the search to make it begin.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.
SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 10.0 – learn more in my book Advanced iOS: Volume One
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.