WWDC 2015 發表 iOS 9 時,除了許多新特性與增強功能,也給開發者一個新機會:讓自家 App 內的內容能透過 Spotlight 被搜尋到並直接使用。新的 API 允許你把 App 內的內容或介面狀態建立索引,讓使用者從 Spotlight 進入。
NSUserActivity:為「可被外部看見的 App 內容」而設計。
Core Spotlight 框架:為任何 App 內容建立索引。
Web markup:適用於內容在某個網站上有鏡像的 App。
本文示範前兩者的用法。
Xcode 7、OS X 10.10 以上、iOS 9.0 以上。
#import <CoreSpotlight/CoreSpotlight.h>
CSSearchableItemAttributeSet *attributeSet =
[[CSSearchableItemAttributeSet alloc] initWithItemContentType:@""];
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);
}
CSSearchableItem *item =
[[CSSearchableItem alloc] initWithUniqueIdentifier:obj.name
domainIdentifier:SearchDomain
attributeSet:attributeSet];
domainIdentifier 是一組內容的分群識別,可用來區分不同類型的內容。
[searchItems addObject:item];
CSSearchableIndex *index = [CSSearchableIndex defaultSearchableIndex];
[index indexSearchableItems:searchItems
completionHandler:^(NSError *error) {
if (error) {
NSLog(@"%@", [error localizedDescription]);
} else {
NSLog(@"indexing successful");
}
}];
使用者從 Spotlight 點選結果進入 App 時,會呼叫 AppDelegate 的這個方法:
- (BOOL)application:(UIApplication *)application
continueUserActivity:(NSUserActivity *)userActivity
restorationHandler:(void (^)(NSArray *restorableObjects))restorationHandler {
UINavigationController *vc = (UINavigationController *)self.window.rootViewController;
[vc.topViewController restoreUserActivityState:userActivity];
return YES;
}
userActivity 裡帶著使用者點擊的那筆資料的所有屬性,可據此決定要跳到哪一頁、顯示什麼內容:
- (void)restoreUserActivityState:(NSUserActivity *)activity {
// 依 activity 攜帶的屬性做相應處理
}
小提醒:索引內容若會變動,記得在資料更新時一併重新索引或刪除舊項目,否則使用者可能搜到已失效的內容。