2015-06-26 12 views

cevap

13
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"); 
}]; 

Not: kUTTypeImage Eğer MobileCoreServices çerçeveyi içe gerektirir.

+0

Küçük resimler, Beta 2 – KIDdAe

+0

'dan beri çalışıyor Kod snippet'iniz için teşekkürler. –

+0

Yanlış görünüyor. "" Com.deeplink ", aslında, indekslediğiniz nesneyi benzersiz şekilde tanımlayan benzersiz bir tanımlayıcı olmalıdır (bir veritabanından veya bir GUUID'den veya başka herhangi birinden birincil kimlik gibi). CSSearchableItemAttributeSet üzerindeki kUTTypeImage, derin bağlantıyı ayarlamanız gereken yerdir. Açılışlarında görüntülenen Apple örneği aslında buggy ve tutarsız, ancak doğru örnek videoda daha önce görülebilir. – strangetimes

35
  1. Yeni iOS projesi oluşturma ve projenize CoreSpotlight ve MobileCoreServices çerçeve ekleyin.

  2. Gerçek CSSearchableItem öğesini ve uniqueIdentifier, domainIdentifier ve attributeSet öğesini ilişkilendirin. Son olarak, aşağıda gösterildiği gibi [[CSSearchableIndex defaultSearchableIndex] ...] kullanarak CSSearchableItem'i endeksleyin. enter image description here

  3. Dizin! @mayqiyue tarafından bahsedilen ama ben de Musluğu işlemek için iOS 8 ile

    - (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"); 
          } 
         }]; 
        } 
    } 
    

    geriye dönük uyumluluk için item değişkenin varlığını kontrol ediyorum ben benzer uygulama kullanıyorum
    enter image description here

+2

İyi cevap. Ancak, muhtemelen, bir kullanıcı seçtikten ve dizine ekledikten sonra geliştiricilerin nasıl harekete geçtiğini eklemelisiniz. – soulshined

+1

HAHA, çünkü çoğu askerler sadece CoreSpotlight arama API'larıyla nasıl başlayacağını bilmiyorlar. İşte sadece basit bir rehber. – mayqiyue

+1

Ben cimri olmuyordum. Bu iyi bir cevaptı, ancak bu soruya gerçek bir cevap vermek için eksik unsurlardı. Gelecekte soru arayanlara dahil olmak güzel olurdu. – soulshined

5

Spotlight'tan arama öğesini AppDelegate uygulamanızda aşağıdaki yöntemi uygulamanız gerekir:

6

Spotlight arama fonksiyonunu tamamlamak için, mayqiyue's cevabını uyguladıktan sonra, sonuçları aramada görebileceksiniz, ancak sonucun seçiminde, uygulamanız ilgili içerikle ilgili görünümü açmayacaktı.

Bunu yapmak için AppDelegate.m ürününüze gidin ve aşağıdaki yöntemi ekleyin.

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 

} 

Swift 2.1

için

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

GÜNCELLEME AppDelegate içinde ithalat emin olun:

-(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
yılında ithalat emin olun. hızlı: Uygulama Delegesi da ana kontrolör Sınıf

-(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]; 
    } 
} 
  • Yaz içinde

    import CoreSpotlight 
    import MobileCoreServices 
    
  • 1
    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} 
    
    +0

    Cevabınıza bir açıklama ekleyebilir misiniz? Teşekkürler – Clarkie

    5
    1. Yaz

      -(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; 
      } 
      
    +0

    @ PeterPan666 teşekkürler –