IOS9-by-Tutorials-Study Notes 2: App-Search

Source: Internet
Author: User

IOS9-by-Tutorials-Study Notes 2: App-Search
IOS9-by-Tutorials-Study Notes 2: App-Search

This article is a summary of my own reading, which may differ from the original book.

IOS 9 launched a search technology that allows users to search for content in the APP in Spotlight. Apple provides three APP Search APIs:
* NSUserActivity
* Core Spotlight
* Web markup

The following is my understanding of these three APIs:
1. NSUserActivity:
NSUserActivity was proposed in ios8. it was proposed to be used as HandOff at that time. In iOS9, it can be used to search for content in the App. We can put some things we want to find in Spotlight into NSUserActivity, and then we can find them in Spotlight. However, there is a limitation that we can only search for the content that users have accessed. Because the userActivity attribute of UIViewController is inherited from UIResponser, The userActivity attribute can be set only when UIViewcontroller is accessed.
2. Core Spotlight:
This is a new technology launched in iOS9 that can search APP content in Spotlight. I understand this technology: Apple provides developers with a global index database. We can put the content we want to search in Spotlight into the database according to Apple's requirements, then Apple did other things to make it searchable. We can also delete the content stored in the database.
3. Web markup:
Web Markup displays the App content on the webpage and compiles the App content into the Spotlight index, so that even if an App is not installed, Apple's indexer can search for a special tag (markup) on the webpage ), search results are displayed on Safari or Spotlight. The details will be detailed in the next article.

Getting started

Next we will start to test related technologies. Here we will use the star project in the book. After this project is run, there are two interfaces:

The following is the project:

The following is an explanation of several key classes marked in the figure:
1. AppDelegate
Click the search result to jump to the program. Some processing will be done in this class first.
2. EmployeeViewController
Detailed interface of the person, which mainly sets NSUserActivity
3. EmployeeService
This is mainly about index-related items in CoreSpotlight.
4. EmployeeSearch
It mainly extends the Employee class and adds search-related attributes.
In addition, some employee-related operations in the project are encapsulated in the target of an EmployeeKit. because they are not in the same module as the primary target, the import is required in the primary target.

The following three options are available in Iphone Setting/Colleagues/Indexing:
* Disabled does not use the Search API, that is, the APP content cannot be searched in Spotlight.
* Only those opened by ViewedRecords can be searched.
* AllRecZ records? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> found + itrzE3Lm7sbvL0cv3tb08L3A + DQo8aDQgaWQ9" Search what we have opened "> Search what we have opened

Using NSUserActivity is relatively simple. You only need to perform the following two steps:
1. Create an NSUserActivity instance and set Related Properties
2. Assign the userActivity attribute to UIViewController

The following code is added to EmployeeSearch:

If the file does not exist, you need to manually create one, and then select EmployeeKit for target.

Import Foundationimport CoreSpotlightextension Employee {// This is used to differentiate Activity and will be used when you click the search result to enter the APP for processing. It can also be used in CoreSpotlight, public static let domainIdentifier = "com. mengxiangyue. colleagues. employee "// The dictionary can be used to obtain the desired public var userActivityUserInfo: [NSObject: AnyObject] {return [" id ": objectId]} // Add the userActivity attribute to the Employee. It is mainly used to obtain the userActivity public var userActivity: NSUserActivity {let activity = NSUserActivity (activityType: Employee. domainIdentifier) activity. title = name // display name activity. userInfo = userActivityUserInfo // data Activity related to the activity. keywords = [email, department] // keyword indicates the keyword to be searched. This record can be searched. Of course, this is just a supplement. No name is added here, you can also search for return activity} by name }}

Here, the Employee is extended and several attributes are added. For the meaning of the attributes, see annotations.
At this time, we need to re-compile the EmployeeKit (because it is not the same target as the main target ).

Next, open EmployeeViewController. swift and add the following code in viewDidLoad:

Let activity = employee. userActivityswitch Setting. searchIndexingPreference {case. disabled: activity. eligibleForSearch = falsecase. viewedRecords: activity. eligibleForSearch = true // relatedUniqueIdentifier defines an id to prevent repeated indexes of NSUserActivity and Core Spotlight. Here, it is set to nil, and the activity will be repeated. contentAttributeSet ?. RelatedUniqueIdentifier = nilcase. AllRecords: activity. eligibleForSearch = true} userActivity = activity

The following method is added to this class to update the Activity at the right time:

// Update the information associated with NSUserActivity override func updateUserActivityState (activity: NSUserActivity) {activity. addUserInfoEntriesFromDictionary (employee. userActivityUserInfo )}

In the Iphone's Setting/Colleagues/Indexing, select ViewedRecords. Start the APP, click Brent Reid in the list to go to the details page, and then use Command + shift + H to calculate the value to the Home page. The drop-down box appears, and enter brent to display the following interface:

The search result page is too ugly. Let's enrich the search result. The search results provided by Apple can be set as follows:

Next we will add the following attributes in EmployeeSearch. swift:

Public var attributeSet: CSSearchableItemAttributeSet {let attributeSet = CSSearchableItemAttributeSet (itemContentType: kUTTypeContact as String) attributeSet. title = name // The buteset that is not clear. contentDescription = "\ (department), \ (title) \ n \ (phone)" attributeSet. thumbnailData = UIImageJPEGRepresentation (loadPicture (), 0.9) attributeSet. supportsPhoneCall = true attributeSet. phoneNumbers = [phone] attributeSet. emailAddresses = [email] attributeSet. keywords = skills attributeSet. relatedUniqueIdentifier = objectId return attributeSet}

The following attributes will be added to the userActivity:

Public var userActivity: NSUserActivity {let activity = NSUserActivity (activityType: Employee. domainIdentifier) activity. title = name activity. userInfo = userActivityUserInfo activity. keywords = [email, department] activity. contentAttributeSet = attributeSet // the newly added return activity}

Then run the program and the search result is as follows:

However, we have noticed that clicking the search result to open the APP does not go to the employee's detailed interface as we expected. This is because we have not done the corresponding processing in the program. Next we will add the following method in AppDelete:

Func application (application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void)-> Bool {let objectId: String // first checks whether a type is defined by ourselves and then obtains the corresponding EmployeeId if userActivity. activityType = Employee. domainIdentifier, let activityObjectId = userActivity. userInfo? ["Id"]? String {objectId = activityObjectId} // obtain the corresponding Employee instance and jump to the corresponding interface if let nav = window ?. RootViewController? UINavigationController, listVC = nav. viewControllers. first? EmployeeListViewController, employee = EmployeeService (). employeeWithObjectId (objectId) {nav. popToRootViewControllerAnimated (false) let employeeViewController = listVC. storyboard ?. InstantiateViewControllerWithIdentifier ("EmployeeView")! Employee viewcontroller. employee = employee nav. pushViewController (employee viewcontroller, animated: false) return true} return false}

At this time, we can click the search result to jump to the corresponding detailed interface.

CoreSpotlight

Next, we will use CoreSpotlight to add the search content. First, set the following attributes in attributeSet of EmployeeSearch. swift:

// In the previous Code, attributeSet. relatedUniqueIdentifier = objectId has been set.

This attribute is mainly used to associate NSUserActivity with Core Spotlight indexed object to prevent repeated content (if repeated content occurs, it is because no id is set when NSUserActivity is tested at the beginning, just restore the simulator)

Then add the following code in EmployeeSearch. swift:

// CoreSpotlight needs to put each item into its index database. Here we create a convenient var searchableItem: CSSearchableItem {let item = CSSearchableItem (uniqueIdentifier: objectId, domainIdentifier: Employee. domainIdentifier, attributeSet: attributeSet) return item}

Then add the following code in EmployeeService. swift:

Import CoreSpotlight .............. <omitted part of the code> public func indexAllEmployees () {let employees = fetchEmployees () let searchableItems = employees. map {$0. searchableItem} // put the item to be indexed into the defaultSearchableIndex CSSearchableIndex. defasearchsearchableindex (). indexSearchableItems (searchableItems) {(error)-> Void in if let error = error {print ("Error indexing employees: \ (error)")} else {print ("Employees indexed. ")}}}

Then select AllRecords in settings. Then, start the APP and search. The search result is as follows:

However, when we click the search result, the result does not respond. You can also guess it. We need to add the code in AppDelete. The final code is as follows:

Func application (application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void)-> Bool {let objectId: String if userActivity. activityType = Employee. domainIdentifier, let activityObjectId = userActivity. userInfo? ["Id"]? String {objectId = activityObjectId} // the newly added else uses different types to distinguish NSUserActivity and CoreSpotlight, and then obtains the corresponding objectId, other processes are the same. // CSSearchableItemActivityIdentifier. This is a key value else if userActivity provided by CoreSpotlight. activityType = CSSearchableItemActionType, let activityObjectId = userActivity. userInfo? [CSSearchableItemActivityIdentifier]? String {objectId = activityObjectId} else {return false} if let nav = window ?. RootViewController? UINavigationController, listVC = nav. viewControllers. first? EmployeeListViewController, employee = EmployeeService (). employeeWithObjectId (objectId) {nav. popToRootViewControllerAnimated (false) let employeeViewController = listVC. storyboard ?. InstantiateViewControllerWithIdentifier ("EmployeeView")! Employee viewcontroller. employee = employee nav. pushViewController (employee viewcontroller, animated: false) return true} return false}

At this time, we should click the search result to jump to the corresponding personnel details.

Delete Item

Finally, delete the indexed Item and modify EmployeeService. swift as follows:

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.")    }  }}

This method is called when the APP is started and Indxing is set to Disabled.

In addition, there are many ways to operate items in CoreSpotlight. I will not write them all here. If you are interested, please refer to the API comments I have translated. Of course, the article may be a bit old, but the basic idea should not change.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.