在 Xamarin.iOS 中使用核心聚焦进行搜索

核心聚焦是 iOS 9 的一个新框架,它提供了一个类似数据库的 API,用于添加、编辑或删除指向应用内内容的链接。 使用核心聚焦添加的项将在 iOS 设备上的聚焦搜索中提供。

有关可以使用核心聚焦编制索引的内容类型的示例,请查看 Apple 的消息、邮件、日历和备忘录应用。 这些应用目前都使用核心聚焦来提供搜索结果。

创建项

下面是使用核心聚焦创建项并为其编制索引的示例:

using CoreSpotlight;
...

// Create attributes to describe an item
var attributes = new CSSearchableItemAttributeSet();
attributes.Title = "App Center Test";
attributes.ContentDescription = "Automatically test your app on 1,000 devices in the cloud.";

// Create item
var item = new CSSearchableItem ("1", "products", attributes);

// Index item
CSSearchableIndex.DefaultSearchableIndex.Index (new CSSearchableItem[]{ item }, (error) => {
    // Successful?
    if (error !=null) {
        Console.WriteLine(error.LocalizedDescription);
    }
});

此信息在搜索结果中如下所示:

核心聚焦搜索结果概述

还原项

当用户点击通过核心聚焦添加到应用的搜索结果中的项时,将调用 AppDelegate 方法 ContinueUserActivity(此方法也用于 NSUserActivity)。 例如:

public override bool ContinueUserActivity (UIApplication application,
   NSUserActivity userActivity, UIApplicationRestorationHandler completionHandler)
{

    // Take action based on the activity type
    switch (userActivity.ActivityType) {
    case "com.xamarin.platform":
        // Restore the state of the app here...
        break;
    default:
        if (userActivity.ActivityType == CSSearchableItem.ActionType.ToString ()) {
            // Display content for searchable item...
        }
        break;
    }

    return true;
}

请注意,这次检查 ActivityTypeCSSearchableItem.ActionType 的活动。

更新项

有时可能需要修改使用核心聚焦创建的索引项,例如需要更改标题或缩略图图像。 若要进行此更改,请使用与最初创建索引时所用的相同方法。 使用与创建项时相同的 ID 创建一个新的 CSSearchableItem,并附加一个包含修改后的属性的新 CSSearchableItemAttributeSet

更新项概述

将此项写入可搜索索引时,将使用新信息更新现有项。

删除项

核心聚焦提供了多种方式来删除不再需要的索引项。

首先,可以按项标识符删除项,例如:

// Delete Items by ID
CSSearchableIndex.DefaultSearchableIndex.Delete(new string[]{"1","16"},(error) => {
    // Successful?
    if (error !=null) {
        Console.WriteLine(error.LocalizedDescription);
    }
});

接下来,可以按其域名删除一组索引项。 例如:

// Delete by Domain Name
CSSearchableIndex.DefaultSearchableIndex.DeleteWithDomain(new string[]{"domain-name"},(error) => {
    // Successful?
    if (error !=null) {
        Console.WriteLine(error.LocalizedDescription);
    }
});

最后,可以使用以下代码删除所有索引项:

// Delete all index items
CSSearchableIndex.DefaultSearchableIndex.DeleteAll((error) => {
    // Successful?
    if (error !=null) {
        Console.WriteLine(error.LocalizedDescription);
    }
});

其他核心聚焦功能

核心聚焦具有以下功能,可帮助保持索引准确且最新:

  • 批量更新支持 - 如果应用需要同时创建或修改一大组索引,则可以在一次调用中将整个批处理发送到 CSSearchableIndex 类的 Index 方法。
  • 响应索引更改 - 使用 CSSearchableIndexDelegate 应用可以响应可搜索索引中的更改和通知。
  • 应用数据保护 - 使用数据保护类,可以为使用核心聚焦添加到可搜索索引的项实现安全性。