iOS9 搜索API

工作需要,研究一下。
iOS搜索API,主要由三种。
1、NSUserActivity,它类似一种历史记录
2、Web Markup,可以在自己的网站进行对苹果索引器的支持。
3、CoreSpotlight,今天的主角。可以讲APP的内容编入索引,供给用户搜索

iOS9 搜索API_第1张图片

可见,这个数据模型至少包括三个简单字段+搜索关键字(数组)

iOS9 搜索API_第2张图片

这个item就是上边的数据模型。

- (void)saveData{
    NSString *obj = @"需要显示的字段";
    // 上图的item
    NSMutableArray *seachableItems = [NSMutableArray new];
    CSSearchableItemAttributeSet *attributeSet = [[CSSearchableItemAttributeSet alloc] initWithItemContentType:@"views"];
    attributeSet.title = obj; // 显示的题目
    attributeSet.contentDescription = [NSString stringWithFormat:NSLocalizedString(@"描述的字段%@", nil),obj];
    // 搜索时的关键字
    attributeSet.keywords = @[@"11",@"22",@"33"];
    // 显示的图片
    UIImage *thumbImage = [UIImage imageNamed:[NSString stringWithFormat:@"image.png"]];
    attributeSet.thumbnailData = UIImagePNGRepresentation(thumbImage);
    // 添加到数组中
    [seachableItems addObject:[[CSSearchableItem alloc]initWithUniqueIdentifier:@"initWithUniqueIdentifier" domainIdentifier:@"domainIdentifier" attributeSet:attributeSet]];
    // 写入到索引CoreSpotlight
    [[CSSearchableIndex defaultSearchableIndex]indexSearchableItems:seachableItems completionHandler:^(NSError * __nullable error) {
        if(error != nil){
            NSLog(@"%@",error.localizedDescription);
        }else {
            NSLog(@"Items were indexed successfully");
        }
    }];

}

用户搜索点击后,在Appdelegate

- (BOOL)application:(nonnull UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray * __nullable))restorationHandler{

    NSString *idetifier = userActivity.userInfo[@"kCSSearchableItemActivityIdentifier"];
// 根据idetifier 判定用户选择的选项,然后处理

    return YES;

}

附:wwdc:https://developer.apple.com/videos/play/wwdc2015-709/

你可能感兴趣的:(iOS9 搜索API)