使用Core Spotlight框架来索引APP内容的一个良好的实践就是当项目不再被需要的时候删除它们。CSSearchableIndex类提供了三种方法来删除可搜索项目:
deleteAllSearchableItemsWithCompletionHandler(:)?
deleteSearchableItemsWithDomainIdentifiers(:completionHandler:)?
deleteSearchableItemsWithIdentifiers(_:completionHandler:)
作为一个示例,添加下面代码到MasterViewController类里的viewDidLoad方法:
CSSearchableIndex.defaultSearchableIndex().deleteSearchableItemsWithDomainIdentifiers(["tv-shows"]) { (error) -> Void in
if error != nil {
print(error?.localizedDescription)
}
else {
// Items were deleted successfully
}
}
再一次的编译运行你的应用。当你想要搜索任何节目时,不会有任何结果返来,因为它们已经在索引当中被删除掉了。
3.联合NSUserActivity和 Core Spotlight
另一个在iOS9中NSUserActivity类的新增特性就是contentAttributeSet属性。这个属性允许你赋予一个CSSearchableItemAttributeSet, 正如你先前创建的那个。这个属性集合(attribute set)允许NSUserActivity对象的搜索结果可以展示如同 Core Spotlight搜索结果那样的相同数量的详细信息。
首先向DetailViewController.swift中最顶部添加下面的imports:
import CoreSpotlight import MobileCoreServices
接下来,用下面的实现代码更新DetailViewController类的configureView方法:
func configureView() {
// Update the user intece for the detail item.
if self.nameLabel != nil && self.detailItem != nil {
self.nameLabel.text = detailItem.name
self.genreLabel.text = detailItem.genre
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .ShortStyle
self.timeLabel.text = dateFormatter.stringFromDate(detailItem.time)
let activity = NSUserActivity(activityType: "com.tutsplus.iOS-9-Search.displayShow")
activity.userInfo = ["name": detailItem.name, "genre": detailItem.genre, "time": detailItem.time]
activity.title = detailItem.name
var keywords = detailItem.name.componentsSeparatedByString(" ")
keywords.append(detailItem.genre)
activity.keywords = Set(keywords)
activity.eligibleForHandoff = false
activity.eligibleForSearch = true
//activity.eligibleForPublicIndexing = true
//activity.expirationDate = NSDate()
let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeItem as String)
attributeSet.title = detailItem.name
attributeSet.contentDescription = detailItem.genre + "\n" + dateFormatter.stringFromDate(detailItem.time)
activity.becomeCurrent()
}
}
最后一次编译运行APP,然后打开一些节目。当你搜索一个节目时,你将会看到你的结果,伴随NSUserActivity的创建,拥有和Core Spotlight 搜索结果相同级别的细节信息。

总结
在这个教程中,你学习到了使用NSUserActivity类和 Core Spotlight框架来使你的应用里的内容可被iOS Spotlight 索引。我也向你展示了怎样使用这两个APIs在你的应用里索引内容以及当一个搜索结果被用户选中时怎样复原你的应用的状态。
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/tongxinshuyu/article-51781-6.html
日俄战争日本伤亡比俄军多几万人
吹牛逼
但这些是极少数