您的位置:首页 > 编程语言 > C语言/C++

IOS9-CoreSpotlight到底怎么用?(OC语言版)

2015-10-10 14:03 357 查看
什么是CoreSpotlight?简单的说:就是在IOS9下,让用户在下拉的搜索页面里可以搜索到你的应用。

#import <Foundation/Foundation.h>

@interface IOS9SearchAPIUtil : NSObject
+(IOS9SearchAPIUtil *)sharedInstance;
-(void)addSearchItemsArray:(NSArray *)array;
@end


#import "IOS9SearchAPIUtil.h"
#import <CoreSpotlight/CoreSpotlight.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <UIKit/UIKit.h>
BOOL IS_IOS_9 = NO;
#define IOS9SearchAPIUtil_domainIdentifier @"com.searchapi.shows"
@implementation IOS9SearchAPIUtil

+(IOS9SearchAPIUtil *)sharedInstance{
static IOS9SearchAPIUtil *instance = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
instance = [[self alloc] init];
});
return instance;
}

-(void)addSearchItemsArray:(NSArray *)array{
if ([[UIDevice currentDevice].systemVersion floatValue]>=9.0) {
IS_IOS_9 = YES;
}

if(IS_IOS_9){
NSMutableArray <CSSearchableItem *> *searchableItems = [NSMutableArray arrayWithCapacity:0];
for (NSDictionary *d in array) {
NSString *title = [d objectForKey:@"title"];
NSString *desc = [d objectForKey:@"desc"];
NSString *time = [d objectForKey:@"time"];
NSString *nid = [d objectForKey:@"nid"];

NSLog(@"d----%@",d);
CSSearchableItemAttributeSet *attributeSet = [[CSSearchableItemAttributeSet alloc]initWithItemContentType:@"SearchAPIViews"];
attributeSet.title = title;
attributeSet.contentDescription = [NSString stringWithFormat:@"%@\n%@",desc,time];
//            NSMutableArray *keywords = [NSMutableArray arrayWithArray:[title split:@" "]];
NSMutableArray *keywords = [NSMutableArray arrayWithArray:[title componentsSeparatedByString:@" "]];
[keywords addObject:desc];
attributeSet.keywords = keywords;
NSString *identifiner = [NSString stringWithFormat:@"%@",nid];

//应该是唯一的,以你的应用程序组。
// REQUIRED因为这是将参考项的方式来更新索引/从索引中删除
//首先是一个UUID,易于使用的,但你可以用自己的UID更换之前,如果你希望该项目第一个索引。
[searchableItems addObject:[[CSSearchableItem alloc]initWithUniqueIdentifier:identifiner domainIdentifier:IOS9SearchAPIUtil_domainIdentifier attributeSet:attributeSet]];
}

[[CSSearchableIndex defaultSearchableIndex]indexSearchableItems:searchableItems completionHandler:^(NSError * __nullable error) {
if(error != nil){
NSLog(@"%@",error.localizedDescription);
}else {
NSLog(@"Items were indexed successfully");
}
}];
}
}

@end


#import "AppDelegate.h"
#import "IOS9SearchAPIUtil.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.

//添加数据源

[[IOS9SearchAPIUtil sharedInstance]addSearchItemsArray:@[@{@"nid":@"fin://1238796",@"title":@"fin",@"desc":@"基金",@"time":@"2014-01-01"},@{@"nid":@"fun://54fdsaf32",@"title":@"fun",@"desc":@"理财",@"time":@"2016-01-01"}]];

return YES;
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: