本文主要是介绍iOS 12新特性 Siri Shortcuts,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
前言
Xcode 10已经正式发布,开发者可以接入Siri Shortcuts的iOS 12新特性。
WWDC2018的Introduction to Siri Shortcuts Session介绍了Siri Shortcuts的使用和Swift接入,但没有Objective-C版本的demo。
于是新开此文,介绍如何快速用OC接入iOS 12新特性Siri Shortcuts。
正文
快速接入Siri Shortcuts
Siri Shortcuts的API有两大类:NSUserActivity和Intents。
使用NSUserActivity接入Siri Shortcuts简单高效。
1、plist添加NSUserActivityTypes(这里定义为 Imy.SiriShortcut
)
2、代码实现,代码下载链接
- (void)viewDidLoad {[super viewDidLoad];UIButton *tempButton = [UIButton buttonWithType:UIButtonTypeSystem];[tempButton setTitle:@"Siri shortcut" forState:UIControlStateNormal];[tempButton addTarget:self action:@selector(reportSiriShortcutAction) forControlEvents:UIControlEventTouchUpInside];tempButton.center = self.view.center;tempButton.bounds = CGRectMake(0, 0, 200, 50);[self.view addSubview:tempButton];
}- (void)reportSiriShortcutAction {NSUserActivity *userActivity = [[NSUserActivity alloc] initWithActivityType:@"Imy.SiriShortcut"];userActivity.eligibleForSearch = YES;if (@available(iOS 12.0, *)) {// 如果要支持老版本,加上判断userActivity.eligibleForPrediction = YES;}userActivity.title = @"SiriShortcut";userActivity.userInfo = @{@"imySiriKey" : @"imySiriValue"};self.userActivity = userActivity;UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"已通知siri" message:userActivity.title preferredStyle:UIAlertControllerStyleAlert];UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {[alertController dismissViewControllerAnimated:YES completion:nil];}];[alertController addAction:sureAction];[self presentViewController:alertController animated:YES completion:nil];
}
AppDelegate文件实现
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {if ([userActivity.activityType isEqualToString:@"Imy.SiriShortcut"]) {//业务处理UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"siri 呼起" message:userActivity.title preferredStyle:UIAlertControllerStyleAlert];UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {[alertController dismissViewControllerAnimated:YES completion:nil];}];[alertController addAction:sureAction];[self.window.rootViewController presentViewController:alertController animated:YES completion:nil];}return YES;
}
Siri Shortcuts的使用效果
iOS 12的开发者选项增加了Display Recent Shortcuts
,打开之后可以显示最近发送给Siri的Shortcuts;
附录
苹果开发者文档
苹果官方的demo
参考文献
这篇关于iOS 12新特性 Siri Shortcuts的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!