在WWDC 2015會議上,蘋果官方公布了iOS9。除開許多新的特性和增強功能,這次升級也給了開發者們一個機會讓他們的app里的內容能通過Spotlight搜索功能被發現和使用。在iOS9中可用的新APIs允許你去索引APP里面的內容或者界面狀態,通過Spotlight來讓用戶使用。 這些新的搜索APIs的三大組件為:
NSUserActivity 類, 它是為可被看見的APP內容而設計的
Core Spotlight 框架, 為任何APP內容而設計的
web markup,為這一類型的APP設計的,就是APP的內容在某個網站上有鏡像
在這里,我將會向你展示可以怎樣在你的應用中使用NSUserActivity類以及 Core Spotlight 框架。
綁定數據源,使其能被搜索
- (void)saveFriend {
NSMutableArray <CSSearchableItem *> *searchableItems = [NSMutableArray array];
// 將Friend里的每個屬性綁定到CSSearchableItemAttributeSet中
for (Friend *friend in self.friendArray) {
CSSearchableItemAttributeSet *attribute = [[CSSearchableItemAttributeSet alloc] initWithItemContentType:@"image"];
attribute.title = friend.name;
attribute.contentDescription = friend.webUrl;
attribute.thumbnailData = UIImagePNGRepresentation(friend.image);
CSSearchableItem *item = [[CSSearchableItem alloc]initWithUniqueIdentifier:friend.f_id domainIdentifier:@"hahahaha" attributeSet:attribute];
[searchableItems addObject:item];
}
[[CSSearchableIndex defaultSearchableIndex] indexSearchableItems:searchableItems completionHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(@"%@",error);
} else {
NSLog(@"被點擊了");
}
}];
}
在App delegate里實現下面的方法能夠處理自定義事件
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler {
NSString *f_id = userActivity.userInfo[@"kCSSearchableItemActivityIdentifier"];
ViewController *vc = (ViewController *)self.window.rootViewController;
[vc loadImage:f_id];
return true;
}
具體請看Demo