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

How to use Core Spotlight to index content in your app

Written by Paul Hudson    @twostraws

One particularly popular feature in iOS 9.0 is the ability to have your app's content appear inside the iOS Spotlight search so that users can search it alongside their other device content.

First up, add these two imports to your class:

import CoreSpotlight
import MobileCoreServices

Now I'm going to give you the code to handle indexing an item, and for this we'll create a method called indxItem() that takes three parameters: the title of the item, a description string for the item, plus a unique identifier. What that unique identifier is depends on you project, but it should be a string. Here's the method:

func indexItem(title: String, desc: String, identifier: String) {
    let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
    attributeSet.title = title
    attributeSet.contentDescription = desc

    let item = CSSearchableItem(uniqueIdentifier: "\(identifier)", domainIdentifier: "com.hackingwithswift", attributeSet: attributeSet)
    CSSearchableIndex.default().indexSearchableItems([item]) { error in
        if let error = error {
            print("Indexing error: \(error.localizedDescription)")
        } else {
            print("Search item successfully indexed!")
        }
    }
}

That wraps the title and description up inside a CSSearchableItemAttributeSet, which in turn goes inside a CSSearchableItem, and from there to Spotlight to index. If you have several items to index you can have them processed all at once and it works faster.

Note that you should change domainIdentifier to your own domain, e.g. com.yoursite.

Now that your item is indexed, it will be available in Spotlight searches immediately. If a user finds one of your index items and taps it, your app will get launched and you should be able to pull out the unique identifier of the item that was tapped – this tells you what item was tapped so that you can take appropriate action.

Put this code inside your app delegate, along with an import for CoreSpotlight:

func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
    if userActivity.activityType == CSSearchableItemActionType {
        if let uniqueIdentifier = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
            doSomethingCoolWith(uniqueIdentifier)
        }
    }

    return true
}

That's it!

For the sake of completeness, here's how you remove an item from the Spotlight index:

func deindexItem(identifier: String) {
    CSSearchableIndex.default().deleteSearchableItems(withIdentifiers: ["\(identifier)"]) { error in
        if let error = error {
            print("Deindexing error: \(error.localizedDescription)")
        } else {
            print("Search item successfully removed!")
        }
    }
}

Available from iOS 9.0 – see Hacking with Swift tutorial 32

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.

Get the ultimate experience

The Swift Power Pack includes my first six books for one low price, helping you jumpstart a new career in iOS development – check it out!

Click here to visit the Hacking with Swift store >>