iOS 9:快速讓你的APP支持spotlight搜索
iOS9中支持為app中的內(nèi)容做索引以支持spotlight搜索,感覺是個很有新意的功能。需要提到的是這些索引是存在本地設(shè)備中的,不會同步到icloud中,更換了設(shè)備就沒有了。
效果就是這樣:
創(chuàng)建支持搜索的內(nèi)容
支持搜索的內(nèi)容的類是CSSearchableItem。
可以展示的屬性有標(biāo)題,一段描述文字,還有縮略圖。這里建議給每個item設(shè)置一個過期時間(expirationDate)。
首先創(chuàng)建表示一個配置展示內(nèi)容的對象CSSearchableItemAttributeSet
- let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeData as String)
- // Add metadata that supplies details about the item.
- attributeSet.title = "July Report.Numbers"
- attributeSet.contentDescription = "iWork Numbers Document"
- attributeSet.thumbnailData = DocumentImage.jpg
attributeSet也支持電話號碼,和地理坐標(biāo)。右邊會有對應(yīng)的動作,如果是支持導(dǎo)航會有一個箭頭。(因為我的app里不需要這功能,我自己沒有試過)
- attributeSet.phoneNumbers;
- attributeSet.latitude;
- attributeSet.longitude;
創(chuàng)建CSSearchableItem
uniqueIdentifier相當(dāng)于這條數(shù)據(jù)的id。domainIdentifier則表示相關(guān)的域。蘋果還提供了一組api對這些索引進行修改刪除操作,domainIdentifier可以當(dāng)做參數(shù),比如可以講一個域下的所有索引刪除。
- let item = CSSearchableItem(uniqueIdentifier: "1", domainIdentifier: "file-1", attributeSet: attributeSet)
將CSSearchableItem添加至系統(tǒng)
- CSSearchableIndex.defaultSearchableIndex().indexSearchableItems([item]) { error in
- if error != nil {
- print(error?.localizedDescription)
- }
- else {
- print("Item indexed.")
- }
- }
tips
大部分的app可能還要兼容iOS8,這里介紹下swift下的判斷方法。
如果是在一個方法里要使用iOS9的api,使用下面來判斷(xcode7也會提醒你)。
- if #available(iOS 9.0, *) {
- }
如果是自己寫的一整個方法想表示只在iOS9可用,用下面的關(guān)鍵字加在方法頭表示
- @available(iOS 9.0, *)
直接貼我的項目代碼了。
用戶搜索后選中打開app的處理
在app delegate里添加這個回調(diào)就好了。
- func application(UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: [AnyObject]? -> Void) -> Bool {
- }
在OC下的方法是這個
- -(BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler{
- }
通過這個可以取到創(chuàng)建CSSearchableItem時設(shè)置的identifier
- NSString* identifier=userActivity.userInfo[CSSearchableItemActivityIdentifier];
接著就可以用這個identifier取出對應(yīng)的數(shù)據(jù),進行處理了。
參考鏈接: