This article explains how to build projects with Shortcuts using OC. Reprint please indicate the source :juejin.cn/post/684490…

Shortcuts is designed to help users navigate complex tasks with a short sentence from Siri. For example, it’s like you give Siri a look, and Siri knows what you’re doing.

Basic process for creating Shortcuts


Shortcuts(Define Shortcut) 2. Configure Shortcuts(Shortcut) 3. Receive Shortcuts callback (Handle Shortcut)

Shortcuts APIs


Shortcuts offers two models for receiving and communicating relevant information in Siri.

NSUserActivity Intents
It is used when the APP needs to be opened for operation It needs to be used when operating directly on the Siri interface
Only index items in Spotlight When you need to add a custom phrase or custom UI to an operation
Siri suggests graininess Siri makes relatively precise suggestions depending on the situation

NSUserActivity:

1. Add NSUserActivityTypes to info.plist


    NSUserActivity *userActivity = [[NSUserActivity alloc] initWithActivityType:@"com.js.sirishortcuts-activity-type"];
    userActivity.eligibleForSearch = YES;
    userActivity.title = @"Here's the title.";
    if(@ the available (iOS 12.0. *)) {userActivity. EligibleForPrediction = YES; // New property, assigned totrueAfter can be exposed to the ` SiriKit ` userActivity. SuggestedInvocationPhrase = @"Taxi home"; / / search keyword} CSSearchableItemAttributeSet * attributes = [[CSSearchableItemAttributeSet alloc] init]; UIImage *icon = [UIImage imageNamed:@"main_icon_jinbi_layer_bao02"];
    attributes.thumbnailData = UIImagePNGRepresentation(icon);
    attributes.contentDescription = @"That's the subtitle."; userActivity.contentAttributeSet = attributes; self.userActivity = userActivity; / / the self as the controllerCopy the code





3. Add the callback in the AppDelegate

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
    if ([userActivity.activityType isEqualToString: @"com.js.sirishortcuts-activity-type"]) {
        NSLog(@"enter");
    }
    return YES;
}
Copy the code

At this point,NSUserActivity is added ~

Intents Usage:

1. Add Intents File File -> New File and select SiriKit Intent Definition File






#import <Foundation/Foundation.h>
#import "GoHomeIntent.h"

NS_ASSUME_NONNULL_BEGIN

@interface GoHomeIntentHandler : NSObject <GoHomeIntentHandling>

@end

NS_ASSUME_NONNULL_END
Copy the code

Implement the protocol method in goHomeintenthandler.m. The lifecycle of an Intent is divided into: Resolve and correct the recipient and message content. Resolve – Confirm – Send the message

@implementation GoHomeIntentHandler
- (void)confirmGoHome:(GoHomeIntent *)intent completion:(void (^)(GoHomeIntentResponse * _Nonnull))completion {
    NSLog(@"confirmGoHome");
}

- (void)handleGoHome:(nonnull GoHomeIntent *)intent completion:(nonnull void (^)(GoHomeIntentResponse * _Nonnull))completion {
    NSLog(@"handleGoHome");
    GoHomeIntentResponse *response = [GoHomeIntentResponse successIntentResponseWithTime:intent.time ?: @""location:intent.location ? : @"" price:@""];
    completion(response);
}

@end
Copy the code

In the intentheader.m file, customize the classes used for receiving

- (id)handlerForIntent:(INIntent *)intent {
    // This is the default implementation.  If you want different objects to handle different intents,
    // you can override this and return the handler you want for that particular intent.
    return [[GoHomeIntentHandler alloc] init];
    //return self;
}
Copy the code

4.Donate Shortcuts

- (void)gotoAddCustomVoiceShortcutView {
    GoHomeIntent *intent = [[GoHomeIntent alloc] init];
    intent.location = @"Chaoyang Men East Road";
    intent.time = @"PM";
    intent.suggestedInvocationPhrase = @"Coming home in the afternoon"; / / hint user INUIAddVoiceShortcutViewController * vc = [[INUIAddVoiceShortcutViewController alloc] initWithShortcut:[[INShortcut alloc] initWithIntent:intent]]; vc.delegate = self; [self presentViewController:vc animated:YES completion:^{ ; }]; / / modify/vc/INUIEditVoiceShortcutViewController * = [[INUIEditVoiceShortcutViewController alloc] initWithVoiceShortcut:voiceShortcut]; // vc.delegate = self; // [self presentViewController:vc animated:YES completion:^{ // ; // }]; }Copy the code

Run Add to see Siri add custom phrases. Click the red button to record. As you can see from the picture below. The variable we entered has been converted to the corresponding copy by the template set in Instents.

Delete donate

1.NSUserActivity

[NSUserActivity deleteSavedUserActivitiesWithPersistentIdentifiers:@[@"com.js.sirishortcuts-activity-type"] completionHandler:^{
}];

[NSUserActivity deleteAllSavedUserActivitiesWithCompletionHandler:^{
}];
Copy the code

2.Shortcuts

[INInteraction deleteInteractionsWithIdentifiers:@[@"ur id"] completion:^(NSError * _Nullable error) {
    ;
}];
[INInteraction deleteAllInteractionsWithCompletion:^(NSError * _Nullable error) {
    ;
}];
[INInteraction deleteInteractionsWithGroupIdentifier:@"ur group id" completion:^(NSError * _Nullable error) {
    ;
}];
Copy the code

test


For debugging purposes,iOS12 gives us the debug option to display the last Shortcuts command in the lock screen and soptlight search screen. You don’t have to tell Siri over and over again. Settings -> Developers -> SHORTCUTS TESTTING

OTHER


Recommended logic for Siri ShortCuts

Siri will be based on the user’s habits. Offer recommended options on the lock screen or search page. And it will change as you use it more and your habits change. Here is an example of WWDC 211 and its official demo

  • NSUserActivity

    As shown in the figure, similar options are selected at similar times every day, and the number of variables is 1. At this time, the system will recommend the ones with more frequency.

    But often events have more than one variable. In the official demo, the variables for the soup are the name of the item, the quantity, the distance to scroll when selecting, and so on.

  • Intens

    Intens provides a uniform template for setting variables when setting Intens.

    The model is abstracted into three cases. Each count will be based on a comprehensive analysis of these three conditions.

Recommended usage rules.

Apple recommends us use the following guidelines to guide users to Siri ShortCuts: 1. Save our Siri ShortCuts results. Make our operation consistent with the results saved by the system. 2. Avoid using variables such as timestamp. Avoid possible implicit dependencies between parameters. And as I said at the beginning. Siri ShortCuts is designed to help users cut down on complex tasks with a short phrase.

There are bound to be some mistakes. If you have any questions, please comment

reference

WWDC 2018: Siri Shortcuts and Access to New Shortcuts