【问题标题】:Is there an example code for corespotlight search feature - iOS 9 API?是否有 corespotlight 搜索功能的示例代码 - iOS 9 API?
【发布时间】:2015-09-12 19:27:45
【问题描述】:

是否有 corespotlight 搜索功能的示例代码 - iOS 9 API?如果可以查看示例代码来实现/测试,真的很感激。

【问题讨论】:

    标签: objective-c xcode7 ios9 corespotlight


    【解决方案1】:
    1. 创建一个新的 iOS 项目并将 CoreSpotlightMobileCoreServices 框架添加到您的项目中。

    2. 创建实际的 CSSearchableItem 并关联 uniqueIdentifier、domainIdentifier 和 attributeSet。最后使用 [[CSSearchableIndex defaultSearchableIndex]...] 对 CSSearchableItem 进行索引,如下所示。

    3. OK!测试索引!

    【讨论】:

    • 好答案。但是您可能应该包括开发人员在用户选择和索引后如何实施操作过程。
    • 哈哈,因为大多数提问者不知道如何开始使用 CoreSpotlight 搜索 API。这里只是一个简单的指南。
    • 我没有开玩笑。这是一个很好的答案,但缺少元素来满足这个问题的真实答案。为将来的问题寻求者包括在内会很好。
    • @DevC 是的,你是对的!框架应该为兼容性弱链接!
    • 数量有限制吗?应用程序可以为 Spotlight 搜索添加的关键字数量?
    【解决方案2】:
    CSSearchableItemAttributeSet *attributeSet;
    attributeSet = [[CSSearchableItemAttributeSet alloc]
                                     initWithItemContentType:(NSString *)kUTTypeImage];
    
    attributeSet.title = @"My First Spotlight Search";
    attributeSet.contentDescription = @"This is my first spotlight Search";
    
    attributeSet.keywords = @[@"Hello", @"Welcome",@"Spotlight"];
    
    UIImage *image = [UIImage imageNamed:@"searchIcon.png"];
    NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
    attributeSet.thumbnailData = imageData;
    
    CSSearchableItem *item = [[CSSearchableItem alloc]
                                           initWithUniqueIdentifier:@"com.deeplink"
                                                   domainIdentifier:@"spotlight.sample"
                                                       attributeSet:attributeSet];
    
    [[CSSearchableIndex defaultSearchableIndex] indexSearchableItems:@[item]
                                     completionHandler: ^(NSError * __nullable error) {
        if (!error)
            NSLog(@"Search item indexed");
    }];
    

    注意:kUTTypeImage 要求您导入 MobileCoreServices 框架。

    【讨论】:

    • 看起来不对。 "com.deeplink" 实际上应该是一个唯一标识符,用于唯一标识您正在编制索引的对象(例如数据库中的主 ID,或 GUID 或其他任何内容)。 CSSearchableItemAttributeSet 上的kUTTypeImage 是您需要设置深层链接的地方。 Apple 在他们的主题演讲中展示的示例实际上是错误且不一致的,但正确的示例可以在视频的前面看到。
    • 我有一个从 Parse 类中提取数据的应用程序,类中的每一行都是一个放入 PFTableViewCell 的对象。索引这些单元格以便可以从聚光灯下搜索它们的最佳方法是什么?
    • 我认为索引数据的最佳方式是在解析类中保存数据。
    • 这是一个用户贡献的类。如果在将数据保存到解析类时进行索引,它只会为那个人编制索引。当用户打开应用程序时,我想为所有这些索引。是否有一个可以工作的 for 循环?
    • @Ayush,你应该用UIImagePNGRepresentation(image)替换[NSData dataWithData:UIImagePNGRepresentation(image)],因为那是多余的。
    【解决方案3】:

    要完成聚光灯搜索功能,一旦您实现了 mayqiyue's 答案,您将能够在搜索中看到结果,但在选择结果时,您的应用将不会打开具有相关内容的相关视图。

    为此,请转到您的 AppDelegate.m 并添加以下方法。

     -(BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler
    
            {
    
                //check if your activity has type search action(i.e. coming from spotlight search)
                if ([userActivity.activityType isEqualToString:CSSearchableItemActionType ] == YES) {
    
                    //the identifier you'll use to open specific views and the content in those views.
                    NSString * identifierPath = [NSString stringWithFormat:@"%@",[userActivity.userInfo objectForKey:CSSearchableItemActivityIdentifier]];
    
                    if (identifierPath != nil) {
    
                        // go to YOUR VIEWCONTROLLER
                        // use notifications or whatever you want to do so
    
                        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
                        MyViewController *myViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];
    
                        // this notification must be registered in MyViewController
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"OpenMyViewController" object: myViewController userInfo:nil];
    
    
                        return YES;
                    }
    
                }
    
    
                return NO;
            }
    

    确保在 AppDelegate.m 中导入

     #import <MobileCoreServices/MobileCoreServices.h>
     #import <CoreSpotlight/CoreSpotlight.h>
    

    Swift 2.1 更新

    func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
    
        if #available(iOS 9.0, *) {
            if userActivity.activityType == CSSearchableItemActionType  {
    
                //the identifier you'll use to open specific views and the content in those views.
                let dict = userActivity.userInfo! as NSDictionary
                let identifierPath  = dict.objectForKey(CSSearchableItemActivityIdentifier) as! String
                if identifierPath.characters.count > 0 {
    
                    let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                    let mvc: MyViewController = storyboard.instantiateViewControllerWithIdentifier("MyViewController") as! MyViewController
    
                    NSNotificationCenter.defaultCenter().postNotificationName("OpenMyViewController", object: mvc, userInfo: nil)
                }
    
                return true
            }
    
        } else {
            // Fallback on earlier versions
                return false
    
        }
    
        return false
    
    }
    

    确保在 AppDelegate.swift 中导入

    import CoreSpotlight
    import MobileCoreServices
    

    【讨论】:

      【解决方案4】:

      我正在使用@mayqiyue 提到的类似实现,但我也在检查item 变量的存在是否与iOS 8 向后兼容。

      - (void)setupCoreSpotlightSearch
      {
          CSSearchableItemAttributeSet *attibuteSet = [[CSSearchableItemAttributeSet alloc] initWithItemContentType:(__bridge NSString *)kUTTypeImage];
          attibuteSet.title = NSLocalizedString(@"Be happy!", @"Be happy!");
          attibuteSet.contentDescription = @"Just like that";
          attibuteSet.keywords = @[@"example", @"stackoverflow", @"beer"];
      
          UIImage *image = [UIImage imageNamed:@"Image"];
          NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
          attibuteSet.thumbnailData = imageData;
      
          CSSearchableItem *item = [[CSSearchableItem alloc] initWithUniqueIdentifier:@"1"
                                                                   domainIdentifier:@"album-1"
                                                                       attributeSet:attibuteSet];
          if (item) {
              [[CSSearchableIndex defaultSearchableIndex] indexSearchableItems:@[item] completionHandler:^(NSError * _Nullable error) {
                  if (!error) {
                      NSLog(@"Search item indexed");
                  }
              }];
          }
      }
      

      要处理 Spotlight 中对搜索项的点击,您需要在 AppDelegate 中实现以下方法:

      - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler
      {
          if ([userActivity.activityType isEqualToString:CSSearchableItemActionType]) {
              NSString *uniqueIdentifier = userActivity.userInfo[CSSearchableItemActivityIdentifier];
      
              // Handle 'uniqueIdentifier'
              NSLog(@"uniqueIdentifier: %@", uniqueIdentifier);
          }
      
          return YES;
      }
      

      【讨论】:

        【解决方案5】:
        1. 写在你的主控制器类中

          -(void)storeValueForSpotligtSearch {
          
              NSString *bundleIdentifier                      = [[NSBundle mainBundle] bundleIdentifier];
              // **Your Model Array that Contain Data Like attributes Make, Model, Variant and Year and Images**
          
              for (MyCatalogeModel *myCatalogeModelObj in yourDataContainer) {
                  NSMutableArray *arrKeywords                 = [[NSMutableArray alloc] initWithObjects: myCatalogeModelObj.year, myCatalogeModelObj.make, myCatalogeModelObj.model, myCatalogeModelObj.variant, nil];
                  NSString *strIdentifier                     = [NSString stringWithFormat:@"%@.%@",bundleIdentifier, myCatalogeModelObj.carId];
                  self.userActivity                           = [[NSUserActivity alloc]initWithActivityType:strIdentifier];
                  self.userActivity.title                     = myCatalogeModelObj.year;
                  self.userActivity.title                     = myCatalogeModelObj.make;
                  self.userActivity.title                     = myCatalogeModelObj.model;
                  self.userActivity.title                     = myCatalogeModelObj.variant;
                  self.userActivity.eligibleForSearch         = YES;
                  self.userActivity.eligibleForPublicIndexing = YES;
                  self.userActivity.eligibleForHandoff        = YES;
                  CSSearchableItemAttributeSet * attributeSet = [[CSSearchableItemAttributeSet alloc] initWithItemContentType:(NSString *)kUTTypeJSON];
                  attributeSet.title                          = myCatalogeModelObj.make;
                  attributeSet.thumbnailData                  = [NSData dataWithContentsOfURL:[NSURL URLWithString:[myCatalogeModelObj.imageArray objectAtIndex:0]]];
                  attributeSet.contentDescription             = [NSString stringWithFormat:@"%@ %@ %@ %@", myCatalogeModelObj.year, myCatalogeModelObj.make, myCatalogeModelObj.model, myCatalogeModelObj.variant];
                  attributeSet.keywords                       = arrKeywords;
                  CSSearchableItem *item                      = [[CSSearchableItem alloc] initWithUniqueIdentifier:strIdentifier domainIdentifier:@"spotlight.CARS24ChannelPartnerapp" attributeSet:attributeSet];
                  [[CSSearchableIndex defaultSearchableIndex] indexSearchableItems:@[item] completionHandler: ^(NSError * __nullable error) {
                  }];
                  self.userActivity.contentAttributeSet       = attributeSet;
                  [self.userActivity becomeCurrent];
                  [self updateUserActivityState:self.userActivity];
              }
          }
          
        2. 在应用代理中写入

          -(BOOL)application:(nonnull UIApplication *) application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray * __nullable))restorationHandler {
          
              @try {
          
                  NSString *strIdentifier;
                  NSNumber *numScreenId;
                  NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
                  NSLog(@"Activity = %@",userActivity.userInfo);
                  if (userActivity.userInfo[@"vc"]) {
                      numScreenId = userActivity.userInfo[@"vc"];
                  }
                  else{
                      strIdentifier = [userActivity.userInfo objectForKey:@"kCSSearchableItemActivityIdentifier"];
                      NSLog(@"strIdentifier : %@",strIdentifier);
                      NSArray *arr = [strIdentifier componentsSeparatedByString:@"."];
                      NSString *strScreenId = [arr objectAtIndex:3];
                      NSLog(@"ID -= %@",strScreenId);
          
                      **// On Click in Spotlight search item move your particular view.**
          
                      [self moveToParticular:[strScreenId intValue]];
                      numScreenId = [numFormatter numberFromString:strScreenId];
                  }
              }
              @catch (NSException *exception) {}
          
              return YES;
          }
          

        【讨论】:

          【解决方案6】:
          let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeImage as String)
          attributeSet.title = "Searchable Item"
          attributeSet.contentDescription = "Code for creating searchable item"
          attributeSet.keywords = ["Item","Searchable","Imagine"]
          attributeSet.thumbnailURL = NSURL(string: "https://blog.imagine.com/")
          
          let searchableItem = CSSearchableItem(uniqueIdentifier: "com.imagine.objectA", domainIdentifier: "spotlight.search", attributeSet: attributeSet)
          CSSearchableIndex.defaultSearchableIndex().indexSearchableItems([searchableItem]) {_ in}
          

          【讨论】:

          • 您能否为您的答案添加解释。谢谢
          猜你喜欢
          • 1970-01-01
          • 2015-12-16
          • 2017-05-03
          • 2015-10-04
          • 2013-09-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多