使用场景
需要Siri打开应用或者在自定义快捷指令打开应用,并携带内容进入应用。
1.创建Intents文件
1.1 依次点开File->New->File
1.2 搜索intent关键字找到 SiriKit Intent Definition File文件
1.3 找到刚才创建的Intent文件,点击+然后New Intent
1.4 LaunchApp根据自己需要来自定义命名
1.5 设置失败和成功提示内容
1.6 设置参数(这里设置了一个名为content的属性,可以根据自己需求添加)
1.7 设置输出content属性
2.创建一个Intent Extension的Targets
2.1 File->New->Targets
2.2 找到Intent Extension并创建
2.3 创建Intent Extension
2.4 配置Intent Extension到Intents
创建之后可以在项目里面看到
找到我们前面配置的Intents文件,关联Intent Extension
2.5 配置IntenHandler.m
导入#import “LaunchAppIntent.h”,关联LaunchAppIntentHandling
实现LaunchAppIntent的函数
- (void)handleLaunchApp:(nonnull LaunchAppIntent *)intent completion:(nonnull void (^)(LaunchAppIntentResponse * _Nonnull))completion {NSUserActivity *userActivity = [[NSUserActivity alloc] initWithActivityType:NSStringFromClass([LaunchAppIntent class])];completion([[LaunchAppIntentResponse alloc] initWithCode:LaunchAppIntentResponseCodeContinueInApp userActivity:userActivity]);
}- (void)confirmLaunchApp:(LaunchAppIntent *)intent completion:(void (^)(LaunchAppIntentResponse * _Nonnull))completion {NSUserActivity *userActivity = [[NSUserActivity alloc] initWithActivityType:NSStringFromClass([LaunchAppIntent class])];LaunchAppIntentResponse *response = [[LaunchAppIntentResponse alloc] initWithCode:LaunchAppIntentResponseCodeReady userActivity:userActivity];completion(response);
}- (void)resolveContentForLaunchApp:(nonnull LaunchAppIntent *)intent withCompletion:(nonnull void (^)(INStringResolutionResult * _Nonnull))completion {if (intent.content != nil && intent.content.length > 0) {completion([INStringResolutionResult successWithResolvedString:intent.content]);} else {completion([INStringResolutionResult needsValue]);}
}
resolveContentForLaunchApp:是你1.6步骤创建的参数content属性,用于代理接收传过来的参数内容。
如果你不走代理模式是不会走这里的,而是会走AppDelegate的application。
2.6 非代理模式下配置AppDelegate的application。
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {if([userActivity.interaction.intent isKindOfClass:[LaunchAppIntent class]]){INInteraction *interaction = userActivity.interaction;LaunchAppIntent *intent = (LaunchAppIntent *)interaction.intent;NSLog(@"application========================%@",intent.content);// 做自己的业务逻辑return YES;
}
3.配置info.plist
<key>NSSiriUsageDescription</key><string>使用Siri控制应用</string><key>NSUserActivityTypes</key><array><string>LaunchAppIntent</string></array>
4.调试
4.1 在快捷指令中添加我们的快捷指令
4.2 输入Launch App
4.3 输入我们需要带进入的属性内容(流程也就结束了)
5.可能出现的错误
5.1 Cycle inside Runner; building could produce unreliable results. This usually can be resolved by moving the shell script phase ‘Thin Binary’ so that it runs before the build phase that depends on its outputs.
Thin Binary执行时机,必须在Copy Bundle Resources和Embed Foundation Extensions执行完成之后。