spotlight在Home界面下拉后搜索
2016-08-31 本文已影响19人
此晨
- 在工程 - General - Linked Frameworks and Libraries 里添加 CoreSpotlight 和 MobileCoreServices 框架,这样就可以用使用 CSSearchableItem 的属性了
2.设置属性
1). searchableItems
var searchableItems = [CSSearchableItem]()
2). 设置searchableItemAttributeSet的属性
//点击了搜索栏里的一项后可在回调里拿到uniqueIdentifier
let searchableItem CSSearchableItem(uniqueIdentifier: "com.appcoda.SpotIt.\(i)", domainIdentifier: "movies", attributeSet: searchableItemAttributeSet)
3). searchableItems.append(searchableItem)
所有代码:
var searchableItems = [CSSearchableItem]()
for i in 0...(moviesInfo.count - 1) {
let movie = moviesInfo[i] as! [String: String]
let searchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
//set the title
searchableItemAttributeSet.title = movie["Title"]!
//set the image
let imagePathParts = movie["Image"]!.componentsSeparatedByString(".")
searchableItemAttributeSet.thumbnailURL = NSBundle.mainBundle().URLForResource(imagePathParts[0], withExtension: imagePathParts[1])
// Set the description.
searchableItemAttributeSet.contentDescription = movie["Description"]!
var keywords = [String]()
let movieCategories = movie["Category"]!.componentsSeparatedByString(", ")
for movieCategory in movieCategories {
keywords.append(movieCategory)
}
let stars = movie["Stars"]!.componentsSeparatedByString(", ")
for star in stars {
keywords.append(star)
}
searchableItemAttributeSet.keywords = keywords
let searchableItem = CSSearchableItem(uniqueIdentifier: "com.appcoda.SpotIt.\(i)", domainIdentifier: "movies", attributeSet: searchableItemAttributeSet)
searchableItems.append(searchableItem)
CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems) { (error) -> Void in
if error != nil {
print(error?.localizedDescription)
}
}
}
4.回调
override func restoreUserActivityState(activity: NSUserActivity) {
if activity.activityType == CSSearchableItemActionType {
if let userInfo = activity.userInfo {
//CSSearchableItemActivityIdentifier对应上面的uniqueIdentifier
let selectedMovie = userInfo[CSSearchableItemActivityIdentifier] as! String
selectedMovieIndex = Int(selectedMovie.componentsSeparatedByString(".").last!)
performSegueWithIdentifier("idSegueShowMovieDetails", sender: self)
}
}
}