iOS9推出了CoreSpotlight,今天没事在家翻译了一部分代码里面的注释,这里贴出了,后面继续贴出实验的文章。
声明:本人大学四级刚过,英语水平有限,所以会有错误,欢迎拍砖。
关于CoreSpotlight的介绍,请读者自己百度、Google。
CoreSpotlight.framework包含的文件如下:
在上面的文件中CSSearchableIndex,用于存储可以被搜索的item;CSSearchableItem,对应存储的itmen;CSSearchableItemAttributeSet,item中存储的相关属性,其他得CSSearchableItemAttributeSet类别都是对应特定的搜索内容的。
下面就贴出代码了(只贴出翻译的代码 有些没有翻译的没有贴出来):
// // CSPerson.h // CoreSpotlight // // Copyright © 2015 Apple. All rights reserved. // #import <CoreSpotlight/CSBase.h> NS_ASSUME_NONNULL_BEGIN NS_CLASS_AVAILABLE(10_11, 9_0) @interface CSPerson : NSObject <NSSecureCoding,NSCopying> - (instancetype)initWithDisplayName:(nullable NSString *)displayName handles:(NSArray<NSString*> *)handles handleIdentifier:(NSString *)handleIdentifier; @property (readonly,nullable) NSString *displayName; //An optional display name for displaying this recipient 展示这个容易的一个可选的名字 @property (readonly) NSArray<NSString*> *handles; //An array of contact handles, e.g. phone numbers 联系人信息的数组 @property (readonly) NSString *handleIdentifier; //A CNContactPropertyKey to identify the type of of handle, e.g. CNContactPhoneNumbersKey 一个CNContactPropertyKey,用于标注信息的类型 @property (copy,nullable) NSString *contactIdentifier; //If the property has already been resolved, the identifier for the Contact 如果属性已经被改变,标志这个联系人得标识 @end NS_ASSUME_NONNULL_END
// // CSSearchableIndex.h // CoreSpotlight // // Copyright © 2015 Apple. All rights reserved. // #import <CoreSpotlight/CSSearchableItem.h> #import <CoreSpotlight/CSBase.h> NS_ASSUME_NONNULL_BEGIN CORESPOTLIGHT_EXPORT NSString * const CSIndexErrorDomain NS_AVAILABLE(10_11, 9_0); typedef NS_ENUM(NSInteger, CSIndexErrorCode) { CSIndexErrorCodeUnknownError = -1, CSIndexErrorCodeIndexUnavailableError = -1000, //The indexer was unavailable CSIndexErrorCodeInvalidItemError = -1001, //The CSSearchableItem is invalid for some reason CSIndexErrorCodeInvalidClientStateError = -1002, //The provided clientState was not valid for some reason CSIndexErrorCodeRemoteConnectionError = -1003, //There was an error trying to communicate with the remote process CSIndexErrorCodeQuotaExceeded = -1004, //Quota for bundle was exceeded } NS_AVAILABLE(10_11, 9_0); NS_CLASS_AVAILABLE(10_11, 9_0) @protocol CSSearchableIndexDelegate; @interface CSSearchableIndex : NSObject @property (weak,nullable) id<CSSearchableIndexDelegate> indexDelegate; + (instancetype)defaultSearchableIndex; - (instancetype)initWithName:(NSString *)name; //Apps can set a default protection class for items in their entitlements. You can alternately create an instance with a custom protection class to use on iOS. It should be one of NSFileProtectionNone, NSFileProtectionComplete, NSFileProtectionCompleteUnlessOpen, or NSFileProtectionCompleteUntilFirstUserAuthentication. // App能够在他们的权限范围内,为items设置一个默认的保护类。你能够选择使用一个在iOS自定义的的保护类创建一个实例。他应该是其中之一:NSFileProtectionNone, NSFileProtectionComplete, NSFileProtectionCompleteUnlessOpen, or NSFileProtectionCompleteUntilFirstUserAuthentication. - (instancetype)initWithName:(NSString *)name protectionClass:(nullable NSString *)protectionClass NS_AVAILABLE_IOS(9_0); // Call this method to add or update items in the index. // Completion handlers will be called once the data has been journaled by the index. If the completion handler returns an error, the client should retry, as it was not journaled correctly. // reindexSearchableItemsWithIdentifiers will be called if the journaling completed successfully but the data was not able to be indexed for some reason. // 调用这个方法在index(索引)中添加更新items // Completion handlers将会在数据被记录入index后调用一次。当数据没有被正确得记录的时候,这个Completion handlers返回error,客户端应该重试。 // 如果数据被正常得记录了,但是由于某些原因数据不能被索引,reindexSearchableItemsWithIdentifiers将会被调用 - (void)indexSearchableItems:(NSArray<CSSearchableItem *> *)items completionHandler:(void (^ __nullable)(NSError * __nullable error))completionHandler; // Call this method to remove items with the given identifiers from the index. // Completion handlers will be called once the data has been journaled by the index. If the completion handler returns an error, the client should retry, as it was not journaled correctly. // reindexSearchableItemsWithIdentifiers will be called if the journaling completed successfully but the data was not able to be indexed for some reason. // 调用这个方法可以从索引里,根据给定的identifiers删除items // Completion handlers将会在数据被记录入index后调用一次。当数据没有被正确得记录的时候,这个Completion handlers返回error,客户端应该重试。 // 如果数据被正常得记录了,但是由于某些原因数据不能被索引,reindexSearchableItemsWithIdentifiers将会被调用 - (void)deleteSearchableItemsWithIdentifiers:(NSArray<NSString *> *)identifiers completionHandler:(void (^ __nullable)(NSError * __nullable error))completionHandler; // Call this method on the index to remove any items from the index with the given domain identifiers. The delete is recursive so if domain identifiers are of the form <account-id>.<mailbox-id>, for example, calling delete with <account-id> will items with that account and any mailbox. // 在索引上调用这个方法,将会根据给定的域标示符(domain identifiers)删除所有得items。如果域标示符(domain identifiers)是这种格式:<account-id>.<mailbox-id>,这个删除将会递归删除。例如:调用删除参数<account-id>,将会删除这个账户下和任何邮箱的items - (void)deleteSearchableItemsWithDomainIdentifiers:(NSArray<NSString *> *)domainIdentifiers completionHandler:(void (^ __nullable)(NSError * __nullable error))completionHandler; // Call this method to delete all searchable items from the index. // 调用这个方法在索引上删除所有的可搜素的items - (void)deleteAllSearchableItemsWithCompletionHandler:(void (^ __nullable)(NSError * __nullable error))completionHandler; @end @interface CSSearchableIndex (CSOptionalBatching) //Batching: //For some clients, it may be beneficial to batch updates to the index. Those clients can use batching and persist client state information (< 250 bytes) in the index. That state information can be used to determine where indexing needs to resume from in case of a client crash or jetsam. Batching is supported for indexSearchableItems deleteSearchableItemsWithIdentifiers. Persisted client state will be reset whenever deleteAllSearchableItemsWithCompletionHandler is called. // 对于一些用户,批量更新所以将会非常便利。用户可以使用批量操作持久化用户的状态信息在索引中。如果客户端crash或者退出,这些状态信息用于决定索引应该在哪里被唤醒(译者注:可能翻译的有问题)。批处理可以支持indexSearchableItems、deleteSearchableItemsWithIdentifiers。当调用deleteAllSearchableItemsWithCompletionHandler方法时候,持久化客户端状态将会被重置。 //Note: Batching is unsupported for the CSSearchableIndex returned by the defaultSearchableIndex method //Note: 对于通过defaultSearchableIndex方法获取的CSSearchableIndex不支持批处理 //Thread safety: In batch mode, the client takes responsibility for protecting the private CSSearchableIndex instance from concurrent access from multiple threads. Concurrent calls to the index instance will have undefined results. beginIndexBatch must not be called again before endIndexBatchWithClientState:completionHandler: has returned (it is however safe to call before the completionHandler passed to endIndexBatchWithClientState:completionHandler has been called). // 线程安全:在批处理模式下,客户端负责保护私有的CSSearchableIndex,处理多线程的同时访问。同时访问索引实例将会有未定义的结果。beginIndexBatch不能在endIndexBatchWithClientState:completionHandler:还没有返回结果前调用。 //Begin a batch of index adds, updates, or deletes. // 开始批出index添加、更新、删除 - (void)beginIndexBatch; //End a batch passing in client state information to be persisted in the index. The completion handler will be called once the client state has been persisted. // 结束一个批处理,传入客户端状态信息在index中去做持久化。completion handler将会在客户端状态被持久化结束后调用一次。 - (void)endIndexBatchWithClientState:(NSData *)clientState completionHandler:(void (^ __nullable)(NSError * __nullable error))completionHandler; // Async fetches the app's last stored client state information. // 异步获取App的最后存储的客户端状态信息。 - (void)fetchLastClientStateWithCompletionHandler:(void (^)(NSData * __nullable clientState,NSError * __nullable error))completionHandler; @end //An application that is long running should provide a CSSearchableIndexDelegate conforming object to handle communication from the index. //Alternatively, an app can provide an extension whose request handler conforms to this protocol and the extension will be called if the app isn't running. // 一个长时间运行的应用程序,应该提供一个CSSearchableIndexDelegate对象,处理index相关的联系。 @protocol CSSearchableIndexDelegate <NSObject> @required // The index requests that the delegate should reindex all of its searchable data and clear any local state that it might have persisted because the index has been lost. // 索引请求这个代理重新索引所有可搜索的数据,并且清除任何本地状态(可能该状态已经被持久化),因为索引已经丢失了。 // The app or extension should call indexSearchableItems on the passed in CSSearchableIndex. // The app or extension must call the acknowledgement handler once any client state information has been persisted, that way, in case of a crash, the indexer can call this again. // If the app passes clientState information in a batch, the acknowledgement can be called right away. // The passed in index shouldn't be used in an extension if a custom protection class is needed. - (void)searchableIndex:(CSSearchableIndex *)searchableIndex reindexAllSearchableItemsWithAcknowledgementHandler:(void (^)(void))acknowledgementHandler; // The index requests that the delegate should reindex the searchable data with the provided identifiers. // 根据给定的identifiers重新索引可搜索的数据 // The app or extension should call indexSearchableItems:completionHandler on the passed in index CSSearchableIndex to update the items' states. // The app or extension must call the acknowledgement handler once any client state information has been persisted, that way, in case of a crash, the indexer can call this again. // If the app passes clientState information in a batch, the acknowledgement can be called right away. // The passed in index shouldn't be used in an extension if a custom protection class is needed. - (void)searchableIndex:(CSSearchableIndex *)searchableIndex reindexSearchableItemsWithIdentifiers:(NSArray <NSString *> *)identifiers acknowledgementHandler:(void (^)(void))acknowledgementHandler; @end NS_ASSUME_NONNULL_END
// // CSSearchableItem.h // CoreSpotlight // // Copyright © 2015 Apple. All rights reserved. // #import <CoreSpotlight/CSBase.h> #import <CoreSpotlight/CSSearchableItemAttributeSet.h> NS_ASSUME_NONNULL_BEGIN // When opening a document from Spotlight, the application's application:willContinueUserActivityWithType: // method will get called with CSSearchableItemActionType, followed by application:continueUserActivity:restorationHandler: with an NSUserActivity where the userInfo dictionary has a single key value pair where CSSearchableItemActivityIdentifier is the key and the value is the uniqueIdentifier used when creating the item. // 当从Spotlight打开一个文档的时候,application的application:willContinueUserActivityWithType方法 CORESPOTLIGHT_EXPORT NSString * const CSSearchableItemActionType; CORESPOTLIGHT_EXPORT NSString * const CSSearchableItemActivityIdentifier; NS_CLASS_AVAILABLE(10_11, 9_0) @interface CSSearchableItem : NSObject <NSSecureCoding, NSCopying> - (instancetype)initWithUniqueIdentifier:(nullable NSString *)uniqueIdentifier //Can be null, one will be generated domainIdentifier:(nullable NSString *)domainIdentifier attributeSet:(CSSearchableItemAttributeSet *)attributeSet; // Should be unique to your application group. // 在你的应用程序群组中,这个应该是唯一值 // REQUIRED since this is the way you will refer to the item to update the index / delete it from the index // 必须的 由于这个是你在索引中更新、删除索引的标识 // Starts with an UUID for ease of use, but you can replace it with an UID of your own before the item is first indexed if you wish. // 使用UUID在这里是一个简单的方法。如果你希望,你也可以在第一次索引前使用你自己定义的UID。 @property (copy) NSString *uniqueIdentifier; // An optional identifier that represents the "domain" or owner of this item. // 一个可选的identifier,用来标识item的域("domain")或者所有者 // This might be an identifier for a mailbox in an account whose indexed data you may want to remove when the account is deleted. // 这个可能用一个账户的邮箱作为identifier来索引数据,并且当账户删除的时候可以根据这个来删除数据。 // In that case the domainIdentifier should be of the form <account-id>.<mailbox-id> where <account-id> and <mailbox-id> should not contains periods. // 一般情况下domainIdentifier应该是这种格式<account-id>.<mailbox-id>,并且不能含有时间 // Calling deleteSearchableItemsWithDomainIdentifiers with <acconut-id>.<mailbox-id> will delete all items with that domain identifier. // 带参数<acconut-id>.<mailbox-id>调用deleteSearchableItemsWithDomainIdentifiers,将会删除这个domain identifier下的所有items // Calling deleteSearchableItemsWithDomainIdentifiers with <acconut-id> will delete all items with <account-id> and any <mailbox-id>. // 单参数<acconut-id>调用deleteSearchableItemsWithDomainIdentifiers将会删除<account-id>和任何<mailbox-id>的items @property (copy, nullable) NSString *domainIdentifier; // Searchable items have an expiration date or time to live. By default it's set to 1 month. // 可搜索的items失效时间,默认一个月 @property (copy, null_resettable) NSDate * expirationDate; // Set of attributes containing meta data for the item // 设置itme attributes包含的元数据 @property (strong) CSSearchableItemAttributeSet *attributeSet; @end NS_ASSUME_NONNULL_END
// // CSSearchableItemAttributeSet.h // CoreSpotlight // // Copyright © 2015 Apple. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreSpotlight/CSBase.h> #import <CoreSpotlight/CSPerson.h> NS_ASSUME_NONNULL_BEGIN NS_CLASS_AVAILABLE(10_11, 9_0) // CSSearchableItemAttribute encapsulates a set of properties of an CSSearchableItem. // CSSearchableItemAttribute set should only be mutated from one thread at a time. Concurrent access to properties has undefined behavior. // CSSearchableItemAttribute包含CSSearchableItem一系列的属性 @interface CSSearchableItemAttributeSet : NSObject <NSCopying,NSSecureCoding> //Creates an attribute set for the given content type. // 根据给定的类型,创建一个attribute set - (instancetype)initWithItemContentType:(nonnull NSString *)itemContentType; @end //CSLocalizedString can be used in place of NSString to support localization //CSLocalizedString能够在NSString需要使用国际化的时候使用 @interface CSLocalizedString : NSString //Takes a dictionary of preferred codes to the localized string for that language // 通过一个包含语言本地码的字典创建 - (instancetype)initWithLocalizedStrings:(NSDictionary *)localizedStrings; //Returns the localized string for the current language // 返回当前语言的本地化字符串 - (NSString *)localizedString; @end //CSCustomAttributeKey allows you to specify a custom attribute as well as various other properties of that attribute. //CSCustomAttributeKey允许你指定自定义的attribute,和attribute的properties NS_CLASS_AVAILABLE(10_11, 9_0) @interface CSCustomAttributeKey : NSObject <NSCopying,NSSecureCoding> //Key names should be ASCII only, with no punctuation other than '_'. // key的名字必须是ASCII,并且不能包含处理'_'的标点符号 //It is recommended keys be of the form "com_mycompany_myapp_keyname" // 建议key的形式是”com_mycompany_myapp_keyname“ //Keys starting with 'kMD' are reserved. // 以'kMD'开头得key时保留的 - (nullable instancetype)initWithKeyName:(NSString *)keyName; - (nullable instancetype)initWithKeyName:(NSString *)keyName searchable:(BOOL)searchable searchableByDefault:(BOOL)searchableByDefault unique:(BOOL)unique multiValued:(BOOL)multiValued NS_DESIGNATED_INITIALIZER; @property (readonly) NSString *keyName; //Can this attribute be searched on? By default, YES // 这个attribute能否被搜到,默认YES @property (readonly,getter=isSearchable) BOOL searchable; //Is this property searchable by default? By default, NO // property能否被搜索到 默认为NO @property (readonly, getter=isSearchableByDefault) BOOL searchableByDefault; //Should values be uniqued to save storage? By default, NO. Set this to YES when there is a small set of known values, or values are likely to be frequently repeating for other reasons. // 值保存的时候是否应该唯一,默认NO。当你知道只有少量的已知的值得时候,设置为YES,或者某些原因值经常被重复。 @property (readonly, getter=isUnique) BOOL unique; //Is this attribute expecting multiple values to be associated with it, i.e. are values arrays? By default, NO // 这个attribute是否希望多个值与它关联,比如是一个值数组,默认NO @property (readonly, getter=isMultiValued) BOOL multiValued; @end //Use these methods to set custom attributes on an attribute set // 使用这些方法在attribute set上设置自定义的attribute //Values must be common plist types (NSString,NSNumber,NSNull,NSData,NSDate) or CSPerson, or arrays (NSArray) of these types. // 值必须是plist能存储的类型、CSPerson或者array,这三种类型。 @interface CSSearchableItemAttributeSet (CSCustomAttributes) - (void)setValue:(nullable id<NSSecureCoding>)value forCustomKey:(CSCustomAttributeKey *)key; - (nullable id<NSSecureCoding>)valueForCustomKey:(CSCustomAttributeKey *)key; @end //Attributes to be indexed for a given NSUserActivity // 根据给定的NSUserActivity,索引Attributes @interface NSUserActivity (CSSearchableItemAttributeSet) @property (nullable, copy) CSSearchableItemAttributeSet *contentAttributeSet; @end NS_ASSUME_NONNULL_END #ifndef CoreSpotlightAPIVersion #import <CoreSpotlight/CSSearchableItemAttributeSet_Categories.h> #endif
// // CSSearchableItemAttributeSet_General.h // CoreSpotlight // // Copyright © 2015 Apple. All rights reserved. // #import <CoreSpotlight/CSSearchableItemAttributeSet.h> @interface CSSearchableItemAttributeSet (CSGeneral) //A localized string to be displayed in the UI for this item. // 这个item在UI中显示的本地化字符串 @property(nullable, copy) NSString *displayName; //An array of localized strings of alternate display names for this item. // 这个item可选的显示name的本地化字符串的数组 @property(nullable, copy) NSArray<NSString*> *alternateNames; //This is the complete path to the item. @property(nullable, copy) NSString *path; //Optional file URL representing the content to be indexed @property(nullable, strong) NSURL *contentURL; //Optional file URL pointing to a thumbnail image for this item // item中缩略图的URL @property(nullable, strong) NSURL *thumbnailURL; //Optional image data for thumbnail for this item // item中缩略图的image data @property(nullable, copy) NSData *thumbnailData; //For activities, this is the unique identifier for the item this activity is related to // 对于activities,这个是该item跟这个activity关联的unique identifier @property(nullable, copy) NSString *relatedUniqueIdentifier; //This is the date that the last metadata attribute was changed. // 最后修改时间 @property(nullable, strong) NSDate *metadataModificationDate; //UTI Type pedigree for an item. Common types can be found in UTCoreTypes.h @property(nullable, copy) NSString *contentType; @property(nullable, copy) NSArray<NSString*> *contentTypeTree; //Represents keywords associated with this particular item. //Example Keywords might be Birthday,Important etc. @property(nullable, copy) NSArray<NSString*> *keywords; //The title of this particular item. //Title of the document, or it could be the title of this mp3 or a subject of a mail message. @property(nullable, copy) NSString *title; @end