美文网首页JZ专题
iOS中Core Spotlight开发

iOS中Core Spotlight开发

作者: iOSCoder_XH | 来源:发表于2016-04-14 17:09 被阅读230次
      iOS随着CoreSpotlight框架的引入,app将支持Spotlight搜索应用中的数据,并快速进入app中进行相关操作。
    

    先看效果图:

    Simulator Screen Shot 2016年4月14日 下午4.51.39.png

    开始开发:
    1、引入CoreSpotlight和MobileCoreServices

    屏幕快照 2016-04-14 下午4.56.27.png
    #import <CoreSpotlight/CoreSpotlight.h>
    #impor <MobileCoreServices/MobileCoreServices.h>
    

    2、保存数据

    //创建SearchableItems的数组
    NSMutableArray *searchableItems = [[NSMutableArray alloc] init];
    //1.创建条目的属性集合
    CSSearchableItemAttributeSet
    * attributeSet = [[CSSearchableItemAttributeSet alloc]
    initWithItemContentType:(NSString*)kUTTypeImage];
    //2.给属性集合添加属性
    attributeSet.title = title;
    attributeSet.contentDescription = desc;
    attributeSet.thumbnailData = UIImagePNGRepresentation(image);
    //3.属性集合与条目进行关联
    CSSearchableItem
    *searchableItem = [[CSSearchableItem alloc]
    initWithUniqueIdentifier:identifier domainIdentifier:domainIdentifier
    attributeSet:attributeSet];
    //把该条目进行暂存
    [searchableItems addObject:searchableItem];
    //4.把条目数组与索引进行关联
    [[CSSearchableIndex
    defaultSearchableIndex] indexSearchableItems:searchableItems
    completionHandler:^(NSError * _Nullable error) {
    if (error) {
    NSLog(@"save spotilight error %s, %@", __FUNCTION__, [error localizedDescription]);
    }
    }];
    

    3、删除相应数据

    [[CSSearchableIndex defaultSearchableIndex] deleteSearchableItemsWithIdentifiers:identifiers completionHandler:^(NSError * _Nullable error) {
    if (error) {
    NSLog(@"del spotilight error %s, %@", __FUNCTION__, [error localizedDescription]);
    }
    }];
    [[CSSearchableIndex defaultSearchableIndex] deleteSearchableItemsWithDomainIdentifiers:domainIdentifiers completionHandler:^(NSError * _Nullable error) {
    if (error) {
    NSLog(@"del domain spotilight error %s, %@", __FUNCTION__, [error localizedDescription]);
    }
    }];
    [[CSSearchableIndex defaultSearchableIndex] deleteAllSearchableItemsWithCompletionHandler:^(NSError * _Nullable error) {
    if (error) {
    NSLog(@"del all spotilight error %s, %@", __FUNCTION__, [error localizedDescription]);
    }
    }];
    

    4、Spotlight搜索点击跳转

    - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler{
    NSString *idetifier = userActivity.userInfo[@"kCSSearchableItemActivityIdentifier"];
    return YES;
    }
    

    最后,运行Demo:https://github.com/iOSXH/iOSTests

    相关文章

      网友评论

      • dedenc:你好,我看了你分享的内容 有几个小问题 想向你请教下 ,就是在关于UniqueIdentifier和domainIdentifier这里。比如我想点击不同的item进行跳转 用户1 用户2 用户3 用户4之类的 可是我怎么区分我该跳到哪一个用户的页面呢 如何根据UniqueIdentifier来区分 还有那个domainIdentifier只有在删除的时候才有用吗,是不是我在点击的事件时候 只能通过userInfo这个字典拿到一个key是吗

      本文标题:iOS中Core Spotlight开发

      本文链接:https://www.haomeiwen.com/subject/zaiglttx.html