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:
- When should use
NSUserActivity, when should useCSSearchableIndex? I see it make same result when search in Spotlight. - Below code call every
viewDidLoadof 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")
}
}
The type of content you're indexing and how the user interacts with it will determine if it's appropriate to use
NSUserActivityorCSSearchableItem.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:
NSUserActivityto index items as users perform activities in your app, such as visiting a navigation point or creating and viewing content.CSSearchableItemdoes not require the user visit the content, unlikeNSUserActivity.CSSearchableItemis not publicly indexable, whileNSUserActivityis.