Search code examples
ioscorespotlight

Use NSUserActivity or Core Spotlight


I read on some tutorial, and found that NSUserActivity for index info when user make an activity, Core Spotlight for index a set of content data in app.

Use NSUserActivity

var activity = NSUserActivity(activityType: "com.example.demo.searchapi")
activity.title = contactEntity.name
activity.userInfo = ["id": contactEntity.uid]
activity.eligibleForSearch = true
activity.keywords = NSSet(array: [contactEntity.name,contactEntity.phoneNumber, contactEntity.email]) as! Set

activity.becomeCurrent()

Use Core Spotlight

let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeContact as String)
attributeSet.title = contactEntity.name
attributeSet.relatedUniqueIdentifier = contactEntity.uid

let searchableItem = CSSearchableItem(uniqueIdentifier: contactEntity.uid, domainIdentifier: "com.example.demo.searchapi", attributeSet: attributeSet)

CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems) { error in  
if let error = error { 
    print("Error indexing: \(error)")
} else {
    print("Indexed.")
}

But I don't think there is difference between two solution result. If user make an activity, I can use Core Spotlight, instead of NSUserActivity. It give me same result.

So, why Apple have to provide two difference solutions which have same result?


Solution

  • I am now including Core Spotlight and NSUserActivity into my apps and I have come to learn some differences.

    As @PGDev stated in your comments, NSUserActivity can be set to publicly be index (on Apples servers), which can then be helpful to be shown on other users' search results. While Core Spotlight is only per device.

    The biggest beneficial difference with NSUserActivity, which applies to my apps, is that the more users perform the same activity, say read the same news story, the more popular that index becomes and can have beneficial outcomes. Apple - Enhance Your Search Results

    • The frequency with which users view your content (which is captured when you use NSUserActivity)
    • The amount of engagement users have with your content (determined by the engagement ratio, which is based on the number of times users tap an item related to your app and the number of app-related items that are displayed in search results)
    • The popularity of a URL in your website and the amount of structured data available