chenzhongbao chenzhongbao - 3 months ago 14
iOS Question

trouble with iOS9 search API NSUserActivity

When I watch videos about iOS9 search API WWDC2015´╝îthere is a demo like this:

var activity:NSUserActivity = NSUserActivity(activityType:"com.yummly.browseRecipe")
activity.title = "Baked Potato Chips"
activity.userInfo = ["id":"http://www.yummly.com/recipe/BPC-983195"]
activity.eligibleForSearch = true
activity.becomeCurrent()


I copy this code to my Xcode and run it, when I search by Spotlight, there is no results. What's wrong with it? Bug for iOS9?

Answer

I did like this, is in objective-C, but you can easily translate to swift

 if ([CSSearchableItemAttributeSet class]) {

CSSearchableItemAttributeSet* attributes = [[CSSearchableItemAttributeSet alloc]initWithItemContentType:@"kUTTypePackage"];//Set you content type

attributes.title = model.name;
attributes.contentDescription = model.description;
attributes.identifier = model.fileURL.lastPathComponent;

UIImage* backImage = [UIImage imageWithData:model.imageData];

if (backImage == nil) {

    attributes.thumbnailData = UIImageJPEGRepresentation([UIImage imageNamed:@"DefaultImage"], 0.5);

}else{

    attributes.thumbnailData = model.imageData;
}

NSString* domainID = @"com.myapp.mycompany";
NSString* uniqueID = model.fileURL.lastPathComponent;
CSSearchableItem* item = [[CSSearchableItem alloc]initWithUniqueIdentifier:uniqueID //value passed from NSUserActivity inside .userInfo
                                                          domainIdentifier:domainID
                                                              attributeSet:attributes];

NSLog(@"Item Attributes:%@",item.attributeSet.identifier);
CSSearchableIndex* index = [CSSearchableIndex defaultSearchableIndex];
[index indexSearchableItems:@[item] completionHandler:^(NSError * _Nullable error) {

    if (!error) {
        NSLog(@"Item \"%@\" indexed",model.name);
    }else{
        NSLog(@"Error, \"%@\" not indexed: %@, %@",model.name,error, error.userInfo);
    }

}];
}else{

    NSLog(@"iOS < 9");
}