iOS随着CoreSpotlight框架的引入,app将支持Spotlight搜索应用中的数据,并快速进入app中进行相关操作。
先看效果图:
开始开发:
1、引入CoreSpotlight和MobileCoreServices
#import <CoreSpotlight/CoreSpotlight.h>
#impor <MobileCoreServices/MobileCoreServices.h>
2、保存数据
//创建SearchableItems的数组
NSMutableArray *searchableItems = [[NSMutableArray alloc] init];
//1.创建条目的属性集合
CSSearchableItemAttributeSet
* attributeSet = [[CSSearchableItemAttributeSet alloc]
initWithItemContentType:(NSString*)kUTTypeImage];
//2.给属性集合添加属性
attributeSet.title = title;
attributeSet.contentDescription = desc;
attributeSet.thumbnailData = UIImagePNGRepresentation(image);
//3.属性集合与条目进行关联
CSSearchableItem
*searchableItem = [[CSSearchableItem alloc]
initWithUniqueIdentifier:identifier domainIdentifier:domainIdentifier
attributeSet:attributeSet];
//把该条目进行暂存
[searchableItems addObject:searchableItem];
//4.把条目数组与索引进行关联
[[CSSearchableIndex
defaultSearchableIndex] indexSearchableItems:searchableItems
completionHandler:^(NSError * _Nullable error) {
if (error) {
NSLog(@"save spotilight error %s, %@", __FUNCTION__, [error localizedDescription]);
}
}];
3、删除相应数据
[[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