【Swift】SpotLight搜索

  SpotLight主要功能是在iOS9系統界面下拉會出現搜索功能界面,在這裏能夠搜索關鍵信息,來展現應用內的內容,而且點擊信息打開應用跳轉具體頁面等操做。這個功能仍是頗有用的,面對這愈來愈多的應用霸佔你手機,給你的應用加上這麼一個搜搜功能,仍是有點不同凡響,主要是提高逼格。api

 一、導入頭文件

import CoreSpotlight
import MobileCoreServices

 二、設置應用內搜索

func indexItem(title: String, desc: String, identifier: String) {
        let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
        attributeSet.title = title
        attributeSet.contentDescription = desc
        attributeSet.keywords = ["abc","cd","efg"]
        let item = CSSearchableItem(uniqueIdentifier: "\(identifier)", domainIdentifier: "Lingye.OopsVoice", attributeSet: attributeSet)
        CSSearchableIndex.default().indexSearchableItems([item]) { error in
            if let error = error {
                print("Indexing error: \(error.localizedDescription)")
            } else {
                print("Search item successfully indexed!")
            }
        }
    }

    func deindexItem(identifier: String) {
        CSSearchableIndex.default().deleteSearchableItems(withIdentifiers: ["\(identifier)"]) { error in
            if let error = error {
                print("Deindexing error: \(error.localizedDescription)")
            } else {
                print("Search item successfully removed!")
            }
        }
    }

 三、在Appdelegate中實現SpotLight搜索

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        if userActivity.activityType == CSSearchableItemActionType {
            if let uniqueIdentifier = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
                deindexItem(identifier: uniqueIdentifier)
            }
        }

        return true
    }
相關文章
相關標籤/搜索