iOS 9-by-T-trotrials-学習ノート2:App-Starch

14162 ワード

iOS 9-by-T-trotrials-学習ノート2:App-Starch
この文章の著作権は作者の所有になります.もし転載するなら、孟祥月CSDNブログに連絡してください.http://blog.csdn.net/mengxiangyue 独立ブログ:http://mengxiangyue.com
本文は自分の読書のための一つの総括であり、原本とは一定の違いがあるかもしれない.
iOS 9は、ユーザーがSpotlightでAPP内部のコンテンツを検索する検索技術を発表した.アップルは三つのAPP Search APIを提供しています.NSUserActivity*Core Spotlight*Web markp
以下は簡単に説明します.この3つのAPIについての理解を示します.1.NSUserActivity:NSUserActivityはiOS 8ですでに取り上げられています.ただ、その時にはHandOffとして使われています.iOS 9では、アプリの内容を検索するために使用できます.私たちはSpotlightで検索したいものをNSUserActivityに入れてSpotlightで検索することができますが、これはちょっと制限があります.ユーザーが訪問した内容を検索するしかないです.UIView ControllerのuserActivity属性はUISponserから継承されているので、UID View controllerが訪問する時だけ、userActivity属性を設定する機会があります.2.Core Spotlight:これはiOS 9で新しく発売された技術で、APPの内容をSpotlightで検索することができます.この技術は私が理解しています.アップルは開発者に全体的なindexデータベースを提供しています.Spotlightで検索できるようにしたい内容をアップルの要求に従ってデータベースに入れて、アップルは他のことをして検索できます.同じように、私たちがデータベースに保存した内容を削除することもできます.3.Web markp:Web MarkpはホームページにAppの内容を表示してSpotlightインデックスに組み込むので、Appがインストールされていなくても、アップルのインデックスはウェブページで特別なマークを検索し、SafariやSpotlightに検索結果を表示することができます.具体的には次の文章で詳しく紹介します.
Getting started
これから関連の技術を試してみます.ここはやはり本の中のスタープロジェクトを利用します.今このプロジェクトが実行された後、二つのインターフェースについて:iOS9-by-Tutorials-学习笔记二:App-Search_第1张图片
以下はこの工事のスクリーンショットです.
以下は図中に表示されているいくつかの重要な種類の説明です.1.アプリDelegateをクリックして検索結果をジャンプしてプログラムに移行します.まずこの種類の中で一定の処理をします.2.EmployeeViewController人員の詳細なインターフェース、この中には主にNSUserActivity 3.EmployeeServiceというものがあります.これは主にCoreSpotlightのindexに関するものを書いています.4.EmployeeSearchは主にEmployee類を拡張しています.検索に関する属性を追加しました.他の工程に従業員が関連する操作は全部一つのEmployetKitに封入されています.したがって、メインタージにはimportが必要です.
IphoneのSetting/Collagues/Indexingには次の3つのオプションがあります.*DispabledはSearch APIを使用しないと、SpotlightでAPPの中のコンテンツを検索できません.*Viewrecordsは開いただけで、*AllRecordsのすべての従業員情報が検索できます.
私たちがすでに開いている内容を検索します.
NSUserActivityを使用してこの比較を簡単に実現して、2つのステップだけでいいです.1.NSUserActivityの一例を作成し、関連する属性を設定します.
下記のコードをEmployee Searchに追加します.
このファイルがない場合は、手動で作成する必要があります.その後、targetはEmployee Kitを選択します.
import Foundation
import CoreSpotlight

extension Employee {
  //       Activity,          APP,         ,      CoreSpotlight    ,    、  index         
  public static let domainIdentifier = "com.mengxiangyue.colleagues.employee"
  //            ,                
  public var userActivityUserInfo: [NSObject: AnyObject] {
    return ["id": objectId]
  }

  //  Employee  userActivity  ,         userActivity
  public var userActivity: NSUserActivity {
    let activity = NSUserActivity(activityType: Employee.domainIdentifier)
    activity.title = name  //      
    activity.userInfo = userActivityUserInfo  //   Activity     
    activity.keywords = [email, department]  //              ,          ,        ,      name,        name  
    return activity
  }
}  
ここでEmployeeを拡張して、いくつかの属性を追加しました.属性の意味はコメントを参照してください.この時はEmployeeKitを再コンパイルしたいです.
以下はEmployee View Controller.swiftを開き、view DidLoad()に下記のコードを追加します.
let activity = employee.userActivity
switch Setting.searchIndexingPreference {
case .Disabled:
  activity.eligibleForSearch = false
case .ViewedRecords:
  activity.eligibleForSearch = true
  // relatedUniqueIdentifier     id   NSUserActivity Core Spotlight    ,     nil,       
  activity.contentAttributeSet?.relatedUniqueIdentifier = nil
case .AllRecords:
  activity.eligibleForSearch = true
}

userActivity = activity
Activityを適切なタイミングで更新するための方法をこのクラスに追加します.
//   NSUserActivity     
  override func updateUserActivityState(activity: NSUserActivity) {
    activity.addUserInfoEntriesFromDictionary(employee.userActivityUserInfo)
  }
以下はIphoneのSetting/Collagues/Indexingの中からViewrecordsを選択します.その後、APPを起動し、リストの中でBrent Reidをクリックして詳細ページに入り、Command+shift+Hを使ってHomeページに計上し、検索ボックスがドロップダウンし、brentを入力して次のインターフェースが現れます.
この検索結果の画面を見て、醜すぎると感じました.この検索結果を豊かにしてみます.アップルが提供する検索結果は以下のような内容に設定できます.
下記の属性はEmployee Search.swiftに追加されます.
public var attributeSet: CSSearchableItemAttributeSet {
  let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeContact as String)
  attributeSet.title = name  //         
  attributeSet.contentDescription = "\(department), \(title)
\(phone)"
attributeSet.thumbnailData = UIImageJPEGRepresentation(loadPicture(), 0.9) attributeSet.supportsPhoneCall = true attributeSet.phoneNumbers = [phone] attributeSet.emailAddresses = [email] attributeSet.keywords = skills attributeSet.relatedUniqueIdentifier = objectId return attributeSet }
次にuserActivityに以下の属性を追加します.
public var userActivity: NSUserActivity {
  let activity = NSUserActivity(activityType: Employee.domainIdentifier)
  activity.title = name
  activity.userInfo = userActivityUserInfo
  activity.keywords = [email, department]
  activity.contentAttributeSet = attributeSet   //        
  return activity
}
その後、プログラムを実行し、検索結果は以下の通りです..
しかし、今私達は検索結果をクリックして、APPを開いても、私達の予想通りにその従業員の詳細なインターフェイスにジャンプしていません.これは私達がプログラムで対応していないので、以下のような方法をアプリDeleteに追加します.
func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
  let objectId: String
  //       type                   EmployeeId
  if userActivity.activityType == Employee.domainIdentifier, let activityObjectId = userActivity.userInfo?["id"] as? String {
    objectId = activityObjectId
  }
  //     Employee             
  if let nav = window?.rootViewController as? UINavigationController, listVC = nav.viewControllers.first as? EmployeeListViewController, employee = EmployeeService().employeeWithObjectId(objectId) {
    nav.popToRootViewControllerAnimated(false)
    let employeeViewController = listVC.storyboard?.instantiateViewControllerWithIdentifier("EmployeeView") as! EmployeeViewController
    employeeViewController.employee = employee
    nav.pushViewController(employeeViewController, animated: false)
    return true
  }
  return false
}   
この時は検索結果をクリックして対応する詳細画面に移動できます.
CoreSpotlight
次はCoreSpotlightを使ってこれらの検索内容を追加します.まず、Employee Search.swiftのatributeSetには、以下のような属性が設定されています.
//               attributeSet.relatedUniqueIdentifier = objectId
この属性は主にNSUserActivityをCore Spotlight indexed objectと関連させ、重複した内容の出現を防ぐためです.
そして、Employee Search.swiftに下記のコードを追加します.
// CoreSpotlight      item         ,          
var searchableItem: CSSearchableItem {
  let item = CSSearchableItem(uniqueIdentifier: objectId, domainIdentifier: Employee.domainIdentifier, attributeSet: attributeSet)
  return item
}
そして、Employee Service.swiftに下記のコードを追加します.
import CoreSpotlight

..............<       >

public func indexAllEmployees() {
  let employees = fetchEmployees()
  let searchableItems = employees.map{ $0.searchableItem }
  //          item   defaultSearchableIndex 
  CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems) { (error) -> Void in
    if let error = error {
      print("Error indexing employees: \(error)")
    } else {
      print("Employees indexed.")
    }
  }
}
設定中にAllRecordsを選択すると、APPを起動して検索します.見た検索結果は以下の通りです.
しかし、この時は検索結果をクリックしても反応がありません.考えてみれば、AppDeleteにコードを追加する必要があります.最終コードは以下の通りです.
func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
    let objectId: String
    if userActivity.activityType == Employee.domainIdentifier, let activityObjectId = userActivity.userInfo?["id"] as? String {
      objectId = activityObjectId
    }
    //    else            type  NSUserActivity CoreSpotlight,       objectId,          
    // CSSearchableItemActivityIdentifier   CoreSpotlight     key 
    else if userActivity.activityType == CSSearchableItemActionType, let activityObjectId = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
      objectId = activityObjectId
    } else {
      return false
    }
    if let nav = window?.rootViewController as? UINavigationController, listVC = nav.viewControllers.first as? EmployeeListViewController, employee = EmployeeService().employeeWithObjectId(objectId) {
      nav.popToRootViewControllerAnimated(false)
      let employeeViewController = listVC.storyboard?.instantiateViewControllerWithIdentifier("EmployeeView") as! EmployeeViewController
      employeeViewController.employee = employee
      nav.pushViewController(employeeViewController, animated: false)
      return true
    }
    return false
  }
この時は検索結果をクリックすれば、対応する人員の詳細にジャンプできます.
Itemを削除
最後に、インデックスされたItemを簡単に削除し、Employee Service.swift対応を修正する方法は以下の通りです.
public func destroyEmployeeIndexing() {
  CSSearchableIndex.defaultSearchableIndex().deleteAllSearchableItemsWithCompletionHandler { (error) -> Void in
    if let error = error {
      print("Error deleting searching employee items: \(error)")
    } else {
      print("Employees indexing deleted.")
    }
  }
}
この方法は、APPが起動し、IndxingがDispabledに設定されたときに呼び出します.
また、CoreSpotlightにはItemに対する操作方法がいくつかあります.ここでは一つ一つ書きません.興味があるなら、私が翻訳したAPIの注釈を見てもいいです.もちろん文章は古いかもしれませんが、基本思想は変わっていないはずです.住所:CoreSpotlight.frame eworkコメント翻訳