iOS-自定义Intent及ShortCut,能通过快捷指令唤醒APP并跳转到指定页面

1.Xcode->New->File->搜索Intent

2.在新建的intent文件中中New intent

3.完善资料,内容可自定义

4.创建Extension,file -> new -> target , 选择 Intents Extension 即可

创建完成后,在intents文件中勾选以下target,否则在扩展里,无法访问到前面创建的Intent类

编译程序,Xcode 会自动生成对应的类,我这里的话会生成 LaunchAppIntent 类,下面需要使用

5.完善IntentHandler

引入上述生成的文件,并写入代理,如果之前未勾选target是无法引入的

在代理中写入,以及点击确认按钮后执行的事件

- (void)handleLaunchApp:(LaunchAppIntent *)intent completion:(void (^)(LaunchAppIntentResponse * _Nonnull))completion {
    completion([[LaunchAppIntentResponse alloc] initWithCode:LaunchAppIntentResponseCodeContinueInApp userActivity:nil]);
}

- (void)confirmLaunchApp:(LaunchAppIntent *)intent completion:(void (^)(LaunchAppIntentResponse * _Nonnull))completion {
    NSUserActivity *userActivity = [[NSUserActivity alloc] initWithActivityType:NSStringFromClass([LaunchAppIntent class])];
    LaunchAppIntentResponse *response = [[LaunchAppIntentResponse alloc] initWithCode:LaunchAppIntentResponseCodeSuccess userActivity:userActivity];
    completion(response);
}

6.在手机快捷指令中可以进行测试,新增快捷指令,搜索Xcode中设置好的,点击完成

点击创建好的指令,即能实现唤起APP,也可通过Siri唤醒,名字按照上述自行定义

7.实现APP自动跳转到制动页面

在AppDelegate中引入你要跳转的界面和intent,唤醒APP会通过一下方法进行执行,设置好快捷指令后将会自动跳转到你设置好的控制器

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
    if([userActivity.interaction.intent isKindOfClass:[LaunchAppIntent class]]){
        ViewController *vc = [ViewController new];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
        self.window.rootViewController = nav;
        ViewController2 *secondVC = [[ViewController2 alloc] init];
        [vc.navigationController pushViewController:secondVC animated:YES];
        return YES;
    }
    return NO;
}

8.如果想进行多种操作,可以在此处设置Parameters,在Parameters内新增变量

demo在这里

猜你喜欢

转载自blog.csdn.net/qq_43441647/article/details/133017285