iOS隨著CoreSpotlight框架的引入氮采,app將支持Spotlight搜索應(yīng)用中的數(shù)據(jù),并快速進(jìn)入app中進(jìn)行相關(guān)操作。
先看效果圖:
Simulator Screen Shot 2016年4月14日 下午4.51.39.png
開(kāi)始開(kāi)發(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.屬性集合與條目進(jìn)行關(guān)聯(lián)
CSSearchableItem
*searchableItem = [[CSSearchableItem alloc]
initWithUniqueIdentifier:identifier domainIdentifier:domainIdentifier
attributeSet:attributeSet];
//把該條目進(jìn)行暫存
[searchableItems addObject:searchableItem];
//4.把條目數(shù)組與索引進(jìn)行關(guān)聯(lián)
[[CSSearchableIndex
defaultSearchableIndex] indexSearchableItems:searchableItems
completionHandler:^(NSError * _Nullable error) {
if (error) {
NSLog(@"save spotilight error %s, %@", __FUNCTION__, [error localizedDescription]);
}
}];
3、刪除相應(yīng)數(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搜索點(diǎn)擊跳轉(zhuǎn)
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler{
NSString *idetifier = userActivity.userInfo[@"kCSSearchableItemActivityIdentifier"];
return YES;
}
最后,運(yùn)行Demo:https://github.com/iOSXH/iOSTests