iOS9搜索API NSUserActivity出现问题

时间:2015-09-08 08:01:24

标签: ios ios9

当我观看有关iOS9搜索API WWDC2015的视频时,有一个这样的演示:

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()

我将此代码复制到我的Xcode并运行它,当我通过Spotlight搜索时,没有结果。它出什么问题了? iOS9的错误?

3 个答案:

答案 0 :(得分:2)

出于某种原因,在调用activity.becomeCurrent()之后,必须保留对NSUserActivity对象的引用。像这样(斯威夫特):

activity.becomeCurrent()
self.lastActivity = activity

其中" lastActivity"是您所在班级的财产。

答案 1 :(得分:1)

我确实喜欢这个,是在Objective-C中,但你可以很容易地转换为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");
}

答案 2 :(得分:0)

您需要将NSUserActivity附加到控制器,如下所示。

controller.userActivity = activity