iOS Swift Tutorial iOS9 Swift2

CoreSpotlight search in iOS9

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.

CoreSpotlight search

 

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.
    }

}

Implemention search in ios

 

About the author

Shrikar

Backend/Infrastructure Engineer by Day. iOS Developer for the rest of the time.

/* ]]> */