В Apple documentation on CoreSpotlight срывается процесс создания и добавления элементов в индекс поиска:
Создать объект CSSearchableItemAttributeSet и указать свойства, которые описывают предмет, который вы хотите индексировать.
Создайте объект CSSearchableItem для представления элемента. Объект CSSearchableItem имеет уникальный идентификатор, который позволяет вам позже ссылаться на .
При необходимости укажите идентификатор домена, чтобы вы могли собирать несколько элементов вместе и управлять ими как группой.
Связать атрибут с элементом поиска.
Добавь необходимый элемент для поиска в индекс.
Вот краткий пример, который я, который показывает, как индекс простой Примечание Класс:
class Note {
var title: String
var description: String
var image: UIImage?
init(title: String, description: String) {
self.title = title
self.description = description
}
}
Тогда в некоторой другой функции, создавать заметки, создать CSSearchableItemAttributeSet
для каждой ноты, создать уникальный CSSearchableItem
из набора атрибутов, а индекс коллекции для поиска предметов:
import CoreSpotlight
import MobileCoreServices
// ...
// Build your Notes data source to index
var notes = [Note]()
notes.append(Note(title: "Grocery List", description: "Buy milk, eggs"))
notes.append(Note(title: "Reminder", description: "Soccer practice at 3"))
let parkingReminder = Note(title: "Reminder", description: "Soccer practice at 3")
parkingReminder.image = UIImage(named: "parkingReminder")
notes.append(parkingReminder)
// The array of items that will be indexed by CoreSpotlight
var searchableItems = [CSSearchableItem]()
for note in notes {
// create an attribute set of type Text, since our reminders are text
let searchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
// If we have an image, add it to the attribute set
if let image = note.image {
searchableItemAttributeSet.thumbnailData = UIImagePNGRepresentation(image)
// you can also use thumbnailURL if your image is coming from a server or the bundle
// searchableItemAttributeSet.thumbnailURL = NSBundle.mainBundle().URLForResource("image", withExtension: "jpg")
}
// set the properties on the item to index
searchableItemAttributeSet.title = note.title
searchableItemAttributeSet.contentDescription = note.description
// Build your keywords
// In this case, I'm tokenizing the title of the note by a space and using the values returned as the keywords
searchableItemAttributeSet.keywords = note.title.componentsSeparatedByString(" ")
// create the searchable item
let searchableItem = CSSearchableItem(uniqueIdentifier: "com.mygreatapp.notes" + ".\(note.title)", domainIdentifier: "notes", attributeSet: searchableItemAttributeSet)
}
// Add our array of searchable items to the Spotlight index
CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems) { (error) in
if let error = error {
// handle failure
print(error)
}
}
Этот пример пчела n адаптировано от AppCoda's How To Use Core Spotlight Framework in iOS 9 руководство.
так что ваши данные являются сообщениями? какие атрибуты вы устанавливаете в настоящее время? предмет или текст? – Wain
Почему вы не можете просто удалить файл .txt в своем приложении. Я знаю, что это будет взлом для вашего дела, но также может решить вашу проблему. Чтобы отключить, установите уникальный идентификатор и получите его в приложении '- (BOOL): (UIApplication *) application continueUserActivity: (nonnull NSUserActivity *) userActivity restoreHandler: (nonnull void (^) (NSArray * _Nullable)) restoreHandler {}' in AppDelegate.m –
@Wain, данные хранятся пользователем, поэтому теоретически это может быть любой текст, его обычная длина составляет около 5000 символов, хотя это может быть любая длина. Я установил заголовок и thumbnailUrl, если элемент появился из Интернета, я также установил contentSources. –