在 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;
}
請注意,這次我們檢查的活動是否具有 ActivityType
CSSearchableItem.ActionType
。
更新專案
有時候,我們需要修改以核心焦點建立的索引專案,例如標題或縮圖影像中的變更。 為了進行這項變更,我們會使用與 最初用來建立索引相同的方法。
我們會使用與 用來建立專案相同的識別碼來建立新的 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);
}
});
其他核心焦點功能
核心焦點具有下列功能,可協助保持索引正確且最新:
- 批次更新支援 – 如果您的應用程式需要同時建立或修改大型索引群組,整個批次就可以在一次呼叫中傳送至
Index
類別的CSSearchableIndex
方法。 - 回應索引變更 – 使用
CSSearchableIndexDelegate
您的應用程式可以回應可搜尋索引的變更和通知。 - 套用資料保護 – 使用數據保護類別,您可以使用核心焦點,在新增至可搜尋索引的項目上實作安全性。