LoginSignup
17
14

More than 5 years have passed since last update.

アプリの内容をSpotlight検索の対象にする

Posted at

iOS9からSpotlightでアプリが保持するコンテンツも検索対象にできるようになりました。
やってみましょう。

コンテンツを検索対象にする

まずはプロジェクトに「CoreSpotight.framework」を追加します。

screen1.png

「CoreSpotlight」と「MobileCoreServices」をimportします。

import CoreSpotlight
import MobileCoreServices

コンテンツを検索インデックスに登録するコードは以下の通り。

// 検索対象の作成
let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeData as String)
attributeSet.title = "恐竜打線復活"
attributeSet.contentDescription = "ドアラが恐竜打線の復活を予言!"
attributeSet.thumbnailData = UIImageJPEGRepresentation(UIImage(named: "109b.jpg")!, 1.0)
let item = CSSearchableItem(uniqueIdentifier: "1", domainIdentifier: "doara1", attributeSet: attributeSet)

// インデックスに登録
CSSearchableIndex.defaultSearchableIndex().indexSearchableItems([item]) { error in
    if error != nil {
        print(error?.localizedDescription)
    }
    else {
        print("追加したよ")
    }
}

CSSearchableItemAttributeSetには「supportsPhoneCall」や「supportsNavigation」プロパティがあり、これらをtrueにすることで検索結果から電話をかけたり地図を表示したりもできます。

上記の例の状態で実行させてSpotlightから「恐竜打線」や「ドアラ」で検索すると検索結果に表示されます。

screen2.png

ここでタップするとアプリが起動します。
その時の処理はAppDelegateで「application:continueUserActivity:restorationHandler」を実装してやれば捕捉できます。

func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
    if userActivity.activityType == CSSearchableItemActionType {
        let uniqueIdentifier = userActivity.userInfo? [CSSearchableItemActivityIdentifier] as? String
        print(uniqueIdentifier)
    }
    return true
}

上記の例だと「1」が出力されます。
これはCSSearchableItemのuniqueIdentifierで指定した値です。
この値を使って適切な画面にナビゲーションしてあげれば良いでしょう。

17
14
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
14