您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

iOS 9 Spotlight 搜尋實作(Objective-C 版)

編輯:iOS 技巧大全

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 以上。

實作步驟

1. 引入框架

#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. 建立搜尋項目

CSSearchableItem *item =
    [[CSSearchableItem alloc] initWithUniqueIdentifier:obj.name
                                      domainIdentifier:SearchDomain
                                         attributeSet:attributeSet];

domainIdentifier 是一組內容的分群識別,可用來區分不同類型的內容。

5. 加入陣列

[searchItems addObject:item];

6. 寫入索引

CSSearchableIndex *index = [CSSearchableIndex defaultSearchableIndex];
[index indexSearchableItems:searchItems
          completionHandler:^(NSError *error) {
    if (error) {
        NSLog(@"%@", [error localizedDescription]);
    } else {
        NSLog(@"indexing successful");
    }
}];

7. 處理使用者點擊搜尋結果

使用者從 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;
}

8. 在目標控制器中還原狀態

userActivity 裡帶著使用者點擊的那筆資料的所有屬性,可據此決定要跳到哪一頁、顯示什麼內容:

- (void)restoreUserActivityState:(NSUserActivity *)activity {
    // 依 activity 攜帶的屬性做相應處理
}

小提醒:索引內容若會變動,記得在資料更新時一併重新索引或刪除舊項目,否則使用者可能搜到已失效的內容。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved