chenzhongbao
chenzhongbao

Reputation: 13

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?

Upvotes: 0

Views: 475

Answers (3)

Feng Yun
Feng Yun

Reputation: 81

You need to attach the NSUserActivity to the controller like below.

controller.userActivity = activity

Upvotes: 0

KeepWalking
KeepWalking

Reputation: 129

For some reason, you must keep a reference to your NSUserActivity object after you call activity.becomeCurrent(). Like this (Swift):

activity.becomeCurrent()
self.lastActivity = activity

where "lastActivity" is a property of the class you are in.

Upvotes: 2

Totka
Totka

Reputation: 627

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

Upvotes: 1

Related Questions