iosios-searchapi

What is difference of CSSearchableIndex and NSUserActivity in Search API? How often call?


I see below code in iOS9Sampler to use Search API in iOS 9. It use both NSUserActivity and CSSearchableIndex. So I want to ask question:

  1. When should use NSUserActivity, when should use CSSearchableIndex? I see it make same result when search in Spotlight.
  2. Below code call every viewDidLoad of view controller. Is it correct? Or should it call only one time? How can I check to call one time?

NSUserActivity

    let activityType = String(format: "%@.%@", uniqueIdentifier, domainIdentifier)
    activity = NSUserActivity(activityType: activityType)
    activity.title = "iOS-9-Sampler_NSUserActivity"
    activity.keywords = Set<String>(arrayLiteral: "dog", "cat", "pig", "sheep")
    activity.eligibleForSearch = true
    activity.becomeCurrent()

Core Spotlight

    let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeImage as String)
    attributeSet.title = "iOS-9-Sampler_CoreSpotlight"
    attributeSet.contentDescription = "iOS-9-Sampler is a code example collection for new features of iOS 9."
    attributeSet.keywords = ["dog", "cat", "bird", "fish"]
    let image = UIImage(named: "m7")!
    let data = UIImagePNGRepresentation(image)
    attributeSet.thumbnailData = data

    let searchableItem = CSSearchableItem(
        uniqueIdentifier: uniqueIdentifier,
        domainIdentifier: domainIdentifier,
        attributeSet: attributeSet)

    CSSearchableIndex.defaultSearchableIndex().indexSearchableItems([searchableItem]) { (error) -> Void in
        if error != nil {
            print("failed with error:\(error)\n")
        }
        else {
            print("Indexed!\n")
        }
    }

Solution

  • The type of content you're indexing and how the user interacts with it will determine if it's appropriate to use NSUserActivity or CSSearchableItem.

    This is explained in the App Search Programming Guide, and examples are provided for a couple different scenarios, so be sure to review this thoroughly. Some notes: