web-dev-qa-db-ja.com

corespotlight検索機能-iOS 9 APIのサンプルコードはありますか?

Corespotlight検索機能-iOS 9 APIのサンプルコードはありますか?実装/テストするサンプルコードをご覧ください。

23
mojo_
  1. 新しいiOSプロジェクトを作成し、プロジェクトにCoreSpotlightおよびMobileCoreServicesフレームワークを追加します。 enter image description here

  2. 実際のCSSearchableItemを作成し、uniqueIdentifier、domainIdentifier、attributeSetを関連付けます。最後に、次のように[[CSSearchableIndex defaultSearchableIndex] ...]を使用してCSSearchableItemのインデックスを作成します。 enter image description here

  3. OK!インデックスをテストしてください!
    enter image description here

37
mayqiyue
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フレームワークをインポートする必要があります。

13
Ayush

スポットライト検索機能を完了するには、mayqiyue's answerを実装すると、検索で結果を見ることができますが、結果を選択すると、単にアプリが関連コンテンツを含む関連ビューではなく開きます。

そのためには、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
8
Umar Farooque

@mayqiyueで述べたのと同様の実装を使用していますが、iOS 8との後方互換性のためにitem変数の存在もチェックしています。

- (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;
}
7
skornos
  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;
    }
    
3
Prabhat Pandey
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}
1
asd