介绍:
在WWDC 2015会议上,苹果官方公布了iOS9。除开许多新的特性和增强功能,这次升级也给了开发者们一个机会让他们的app里的内容能通过Spotlight 搜索功能被发现和使用。在iOS9中可用的新APIs允许你去索引APP里面的内容或者界面状态,通过Spotlight来让用户使用。 这些新的搜索APIs的三大组件为:
* NSUserActivity 类, 它是为可被看见的APP内容而设计的??
* Core Spotlight 框架, 为任何APP内容而设计的 ??
* web markup,为这一类型的APP设计的,就是APP的内容在某个网站上有镜像?
在这个教程里,我将会向你展示可以怎样在你的应用中使用NSUserActivity类以及 Core Spotlight 框架。
准备工作:
这个教程需要你运行在Xcode7 和OSX 10.10、iOS9.0系统或更后的系统
步骤:
#import <CoreSpotlight/CoreSpotlight.h>
2.创建搜索属性对象
CSSearchableItemAttributeSet * attributeSet = [[CSSearchableItemAttributeSet alloc] initWithItemContentType:@""];
3.设置搜索属性
//搜索显示的名称
attributeSet.title = obj.name;
//显示的描述
attributeSet.contentDescription = obj.desc;
//搜索关键字
attributeSet.keywords = @[obj.name,@"CX"];
//显示的图标
UIImage * icon = [UIImage imageNamed:obj.imageName];
if (icon) {
attributeSet.thumbnailData = UIImageJPEGRepresentation(icon, 1);
}
4.根据搜索属性创建搜索对象(domainIdentifier:唯一标识)
CSSearchableItem * item = [[CSSearchableItem alloc] initWithUniqueIdentifier:obj.name domainIdentifier:SearchDomain attributeSet:attributeSet];
5.将搜索对象添加到搜索数组
[searchItems addObject:item];
6.设置索引目录
CSSearchableIndex * searchableIndex = [CSSearchableIndex defaultSearchableIndex];
[searchableIndex indexSearchableItems:searchItems completionHandler:^(NSError * _Nullable error) {
if (error != nil) {//添加索引失败
NSLog(@"%@",[error localizedDescription]);
}else{//成功
NSLog(@"indexing successful");
}
}];
7.实现AppDelegate方法(用户通过spotlight搜索到APP里面的内容 点击内容进入APP 就会调用这个方法)
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler{
UINavigationController * vc = (UINavigationController *)self.window.rootViewController;
[vc.topViewController restoreUserActivityState:userActivity];
return YES;
}
8.在搜索列表控制器实现方法(activity里面有用户点击spotlight搜索列表中某条数据的所有属性 根据属性做相应的操作)
- (void)restoreUserActivityState:(NSUserActivity *)activity{}
代码地址