介紹:
在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{}
代碼地址