创建 NSUserActivity

要创建 NSUserActivity 对象,你的应用必须在其 Info.plist 文件中声明它支持的活动类型。支持的活动由你的应用程序定义,并且应该是唯一的。使用反向域样式命名方案(即“com.companyName.productName.activityName”)定义活动。以下是 Info.plist 中的条目可能如下所示:

NSUserActivityTypes [阵列]
- item0 com.companyName.productName.activityName01
- item1 com.companyName.productName.activityName02

一旦定义了所有支持的活动类型,你就可以开始在应用程序的代码中访问和使用它们。

要创建 NSUserActivity 对象,你必须执行以下操作

// Initialize the activity object and set its type from one of the ones specified in your app's plist
NSUserActivity *currentActivity = [[NSUserActivity alloc] initWithActivityType:@"com.companyName.productName.activityName01"];

// Set the title of the activity.
// This title may be displayed to the user, so make sure it is localized and human-readable
currentActivity.title = @"Current Activity";

// Configure additional properties like userInfo which will be included in the activity
currentActivity.userInfo = @{@"informationKey" : @"value"};

// Configure the activity so the system knows what may be done with it
// It is important that you only set YES to tasks that your application supports
// In this example, we will only enable the activity for use with Handoff
[currentActivity setEligibleForHandoff:YES];
[currentActivity setEligibleForSearch:NO]; // Defaults to NO
[currentActivity setEligibleForPublicIndexing:NO]; // Defaults to NO

// Set this activity as the current user activity
// Only one activity may be current at a time on a device. Calling this method invalidates any other current activities.
[currentActivity becomeCurrent];

在此之后,上面的活动应该可用于 Handoff(尽管需要更多的工作才能正确处理切换)。