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
參考文獻

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章