0

Search App Content With Core Spotlight

Introduction

The Core Spotlight (CS) framework is part of a greater collection of APIs, known as Search APIs, which give the opportunity to programmers to increase the discoverability, visibility and ease of access of their apps significantly, and in a fashion that wasn’t possible to be used in earlier versions of iOS.This allow you to index any content or interface state within your app, making it accessible to your users through Spotlight. The three components of these new search APIs are:

  • the NSUserActivity class, which is designed for viewed app content
  • the Core Spotlight framework, which is designed for any app content
  • web markup, designed for apps that have content that is mirrored on a website

The Core Spotlight framework makes the data of an app searchable on the Spotlight, and subsequently bring results regarding an app along with any other results that the system returns. The “heart” of that process lies to the fact that developers have to “ask” iOS to index their app’s data, which must be described in a specific way prior to that.

Getting Started

For quick start Starter Project is given for following tutorial. As this tutorial is about using Core Spotlight we will skip the part of building the app. The starter App lists Employee by their Names and addresses. Instead of using Database, plist has been used as Data Source. By clicking add button we can add new Employee info (name, address) and by clicking any employee from the list it shows detail and can be updated also.

Screen Shot 2016-11-04 at 12.03.32 PM.png

Screen Shot 2016-11-04 at 12.03.51 PM.png

Now first of all, we need to add CoreSpotlight and MobileCoreServices frameworks. To do this open the project and navigate to the General tab in the project settings. Press "+" button under the "Linked Frameworks and Libraries" section:

Screen Shot 2016-11-04 at 11.44.01 AM.png

Open EmployeeCreateController and import the following frameworks along with UIkit.

import CoreSpotLight
import MobileCoreServices

Now add a new function addToSpotlight to EmployeeCreateController. In this function we mainly add the attributes which will be searchable, for example both name and address are searchable and indexed by a unique identifier which is the employee Index. This index will be used later to map the search item from search result to employee detail information.

func addToSpotlight(employee: Dictionary<String,String>) {
        let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
        attributeSet.title = employee["name"]
        attributeSet.contentDescription = employee["address"]

        let searchItem = CSSearchableItem(uniqueIdentifier: "\(employeeIndex)", domainIdentifier: "xyz.Test", attributeSet: attributeSet)
        CSSearchableIndex.defaultSearchableIndex().indexSearchableItems([searchItem]) {(error:NSError?) -> Void in
            if error != nil {
                print(error!.localizedDescription)
            }
        }
    }

inside employeeSaveAction call this function so that each time an employee is added or updated it adds the employee info to searchable contents.

addToSpotlight(getEmployee())

now if you go to app search and search for employee by name or address you can find it.

Screen Shot 2016-11-04 at 12.02.54 PM.png

For going to the detail of the search content we go to app delegate import the required frameworks again and add the following function:

func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
        if userActivity.activityType == CSSearchableItemActionType {
          let identifier = userActivity.userInfo![CSSearchableItemActivityIdentifier]
          NSNotificationCenter.defaultCenter().postNotificationName("DisplaySearchResult", object: identifier)
       }
        return true
    }

add the following line in EmployeeListController to get the searched employee Index

var searchEmployeeIndex: Int!

add in viewDidLoad() the observer to get the Search Result.

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.displaySearchResult(_:)), name: "DisplaySearchResult", object: nil)

add function displaySearchResult to get the search employee index to show Detail of the employee

 func displaySearchResult(notification: NSNotification) {
        searchEmployeeIndex = Int((notification.object as! String))
        self.performSegueWithIdentifier("show", sender: self)
    }

edit prepareForSegue in case employee selection in from search Result or from employee list tableview

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let employeeVC = segue.destinationViewController as! EmployeeCreateController
        if segue.identifier == "create" {
            if employeeDictionary != nil {
                employeeVC.employeeDictionary = employeeDictionary
            }
        } else if segue.identifier == "show" {
            employeeVC.employeeDictionary = employeeDictionary
            let indexPath = self.tableView.indexPathForSelectedRow
            if searchEmployeeIndex != nil { // coming from spotlight
                employeeVC.employeeIndex = searchEmployeeIndex
                employeeVC.employeeToDisplay = employeeListArray[searchEmployeeIndex]
            } else { // coming from tableview
                employeeVC.employeeToDisplay = employeeListArray[(indexPath?.row)!]
                employeeVC.employeeIndex = (indexPath?.row)!
            }
        }
    }

Conclusion

In this tutorial, we learned how to make application's content accessible through iOS Spotlight by using the NSUserActivity class and the Core Spotlight framework. These search APIs are very easy to use and make application's content easier to discover and more accessible to application's users. For more information refer to this document


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí