iOS隨著CoreSpotlight框架的引入,app將支持Spotlight搜索應用中的數(shù)據(jù),并快速進入app中進行相關操作。
先看效果圖:

Simulator Screen Shot 2016年4月14日 下午4.51.39.png
開始開發(fā):
1、引入CoreSpotlight和MobileCoreServices

屏幕快照 2016-04-14 下午4.56.27.png
#import <CoreSpotlight/CoreSpotlight.h>
#impor <MobileCoreServices/MobileCoreServices.h>
2、保存數(shù)據(jù)
//創(chuàng)建SearchableItems的數(shù)組
NSMutableArray *searchableItems = [[NSMutableArray alloc] init];
//1.創(chuàng)建條目的屬性集合
CSSearchableItemAttributeSet
* attributeSet = [[CSSearchableItemAttributeSet alloc]
initWithItemContentType:(NSString*)kUTTypeImage];
//2.給屬性集合添加屬性
attributeSet.title = title;
attributeSet.contentDescription = desc;
attributeSet.thumbnailData = UIImagePNGRepresentation(image);
//3.屬性集合與條目進行關聯(lián)
CSSearchableItem
*searchableItem = [[CSSearchableItem alloc]
initWithUniqueIdentifier:identifier domainIdentifier:domainIdentifier
attributeSet:attributeSet];
//把該條目進行暫存
[searchableItems addObject:searchableItem];
//4.把條目數(shù)組與索引進行關聯(lián)
[[CSSearchableIndex
defaultSearchableIndex] indexSearchableItems:searchableItems
completionHandler:^(NSError * _Nullable error) {
if (error) {
NSLog(@"save spotilight error %s, %@", __FUNCTION__, [error localizedDescription]);
}
}];
3、刪除相應數(shù)據(jù)
[[CSSearchableIndex defaultSearchableIndex] deleteSearchableItemsWithIdentifiers:identifiers completionHandler:^(NSError * _Nullable error) {
if (error) {
NSLog(@"del spotilight error %s, %@", __FUNCTION__, [error localizedDescription]);
}
}];
[[CSSearchableIndex defaultSearchableIndex] deleteSearchableItemsWithDomainIdentifiers:domainIdentifiers completionHandler:^(NSError * _Nullable error) {
if (error) {
NSLog(@"del domain spotilight error %s, %@", __FUNCTION__, [error localizedDescription]);
}
}];
[[CSSearchableIndex defaultSearchableIndex] deleteAllSearchableItemsWithCompletionHandler:^(NSError * _Nullable error) {
if (error) {
NSLog(@"del all spotilight error %s, %@", __FUNCTION__, [error localizedDescription]);
}
}];
4、Spotlight搜索點擊跳轉
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler{
NSString *idetifier = userActivity.userInfo[@"kCSSearchableItemActivityIdentifier"];
return YES;
}
最后,運行Demo:https://github.com/iOSXH/iOSTests