CoreSpotlight search in iOS9

June 15, 2015
Shrikar Archak

<Image alt="CoreSpotlight search" objectFit="contain" src="/static/images/search.png" height={250} width={1000} placeholder="blur" quality={100} />

iOS app search is one of the most powerful feature introduced by Apple in WWDC 2015. App search will help people to discover the content in your app who are interested in searching for keywords indexed by your app.

There are three types of search capabilities provided in iOS

  • NSUserActivity to make the app activites and the state searchable. ( Can index the content through global index)
  • CoreSpotlight to index the content locally.
  • Web Markup if your website replicates the data in your app.

In this example we will focus on CoreSpotlight search. Before we continue go to the build settings and add CoreSpotlight and MobileCoreServices framework to your project.

<Image alt="CoreSpotlight search" objectFit="contain" src="/static/images/Screen-Shot-2015-06-14-at-9.31.04-PM-1024x489.png" height={250} width={1000} placeholder="blur" quality={100} />

 

We need to first create an attribute set which will defines the necessary properties like title, contentDescription and more. Be clear on what you put in these properties as they are used for indexing your item much like google search index.

One more key thing to notice is that the id should be unique for any given domainIdentifier. So make sure each item you are indexing gets its own id. If you use the same id the index will be overwritten.

Now we need to create the actual CSSearchableItem and associating the uniqueIdentifier, domainIdentifier and the attributeSet. Finally index the CSSearchableItem using CSSearchableIndex.defaultSearchableIndex() as show below.

import UIKit
import CoreSpotlight
import MobileCoreServices
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let atset:CSSearchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
        atset.title = "iOS Rocks!!"
        atset.contentDescription = "iOS Rocks!!!"

        let item = CSSearchableItem(uniqueIdentifier: "id1", domainIdentifier: "com.shrikar.iOS9Sample.search", attributeSet: atset)

        CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(\[item\]) { (error) -> Void in
            print("Indexed")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

<Image alt="CoreSpotlight search" objectFit="contain" src="/static/images/Screen-Shot-2015-06-14-at-9.38.10-PM-558x1024.png" height={250} width={1000} placeholder="blur" quality={100} />

Subscribe to the newsletter

Get notified when new content or topic is released.

You won't receive any spam! ✌️