Make App Activities and States Searchable by using NSUserActivity

4.7k views Asked by At

Following is the code that I am trying to implement to make app activities and states searchable but not able to show on iOS search

NSUserActivity *userActivity = [[NSUserActivity alloc]initWithActivityType:@"com.mycompany.activity-type"];

userActivity.title = @"Hello world from in app search";
userActivity.keywords = [NSSet setWithArray:@[@"Hello",@"Welcome", @"search"]];
userActivity.userInfo = @{@"id":@"com.example.state"};

userActivity.eligibleForSearch = YES;    
[userActivity becomeCurrent];

Link to make my question more clear.

4

There are 4 answers

0
Zoltán Lippai On

What I have found is you have to assign the NSUserActivity instance you have created to your currently visible UIViewControllers's userActivity property before calling -becomeCurrent. It has fixed it for me and the items immediately appeared both for handoff on other devices and in spotlight search on the same device.

1
Omar Abdelhafith On

I was experiencing the same issue, and I read on the dev forums that in seed 1 it only works on the device. I was able to make it work on the device.

It might be that this, as with handoff, will only work on the device sadly.

1
L A On

From the Apple Forums:

One thing that has bitten a few people (myself included) is that the activity must not be deallocated. If your code is only working with NSUserActivities (i.e. not using CoreSpotlight in addition) then make sure your activities aren't being deallocated immediately.
In my case, I had code that was allocating the NSUA, setting some properties on it, calling becomeCurrent, but then the object would go out of scope and deallocated. If you're doing this, try tossing the activity into a strong property to see if you can then see the results when you search.

https://forums.developer.apple.com/message/13640#13640

0
k1th On

I couldn't get it to work with beta 2 either. Using a CSSearchableItemAttributeSet with

CSSearchableItemAttributeSet* attributeSet = [[CSSearchableItemAttributeSet alloc] initWithItemContentType:(NSString*)kUTTypeImage];
attributeSet.title = myobject.title;
attributeSet.keywords = [myobject.desc componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
attributeSet.contentDescription = myobject.desc;
if (myobject.images.count > 0) {
    attributeSet.thumbnailData = myobject.myimagedata;
}
attributeSet.rating = @(myobject.rating.integerValue / 2);

CSSearchableItem* item;
item = [[CSSearchableItem alloc] initWithUniqueIdentifier:@"..." domainIdentifier:@"..." attributeSet:attributeSet];
[[CSSearchableIndex defaultSearchableIndex] indexSearchableItems:@[item] completionHandler: ^(NSError * __nullable error) {
    NSLog(@"Search item indexed");
}];

works, though, even with images. What I couldn't get to work was the rating to show up anywhere.