Author: AppCoda, 2018-07-11 Translator: Hale; Proofreading: Liberalisman, Numbbbbb, Yousanflics; Finalized: Forelax

At its 2018 Developer Conference in SAN Jose, Apple announced Siri Shortcuts, a long-awaited feature that will give developers the ability to extend and enhance Siri’s capabilities in their apps. Before that, the SiriKit SDK had very limited features. With Siri Shortcuts, developers can extend Siri’s capabilities and evoke apps by building custom voice actions.

Siri Shortcuts, brief

Siri Shortcuts is all about automation. Siri Shortcuts are an evolution of Workflow, an iOS automation app developed by a former WWDC scholar. Workflow was acquired by Apple in 2017, but even after the acquisition, the App was still available independently on the App Store.

Shortcuts let you expose your app’s functionality to Siri.

Apple’s new Siri Shortcuts borrow a lot from Workflow. But it’s important to distinguish between voice Shortcuts and Shortcuts apps themselves. While the Shortcuts app allows users to create common daily tasks based on spoken phrases, Siri Shortcuts gives developers the ability to extend Siri’s capabilities in their native apps.

At the time of this writing, the Shortcuts app cannot be tested in the iOS 12 Beta 2 Build. So, let’s explore the utility of Siri Shortcuts in the custom apps we’ve built.

Our sample project

Note: This tutorial assumes basic familiarity with the NSUserActivity API. If you’re not familiar with it, check out our excellent tutorial on this topic.

In this tutorial, we’ll explore how to leverage Siri Shortcuts in a simple project by launching our app and displaying a UIAlertView when the user says a phrase like “Say Hi”.

This application provides a brief overview of how to integrate Siri Shortcuts without adding complex code to a large project. By the end of this tutorial, you should have a solid grasp of the use cases and techniques behind Siri Shortcuts and know how to integrate them with your apps!

Define your Shortcuts for a new project

When we are creating any new project, it is important to take some time to establish the basic project structure. First we need to have the latest developer previews for iOS 12, macOS Mojave and Xcode 10. If you haven’t already installed these, you can download them from the developer website.

Create an application called SiriShortcuts in Xcode. Set the organization ID to com.appcoda, which can be changed later as needed.

In Project Settings, select Capabilities and enable Siri, as shown below. We can then use the Siri SDK in the application and add the.Entitlements file to the project.

After Siri is enabled, Xcode adds.Entitlements files to the project. Then add Intents. Framework, a new framework, to the project.

Finally, add NSUserActivityTypes to info.plist. The value of this item should include your Bundle ID and the action to wake up Siri, such as “sayHi”.

Integrated Shortcut

To create a Shortcut application, we first configure Shortcut and then integrate Shortcut into the project

Now that our project has completed all the configuration work for Shortcut, it’s time to integrate Shortcut into the project.

According to Apple developer documentation,

You should do a Shortcut integration every time a user performs an action in your application. For example, if a user can order soup from a restaurant using your app, make a Shortcut integration for the payment operation after the user places the order. If the user does not perform operations in your application, there is no need to perform integration operations.

Clearly, we only need to integrate Shortcut to enhance the overall functionality of the application if we provide meaningful use cases.

Back in the code, first we go to the viewController.swift file. After the viewDidLoad method, create a new method called setupIntents. In this method, implement our Siri Shortcuts code.

func setupIntents(a) {
        let activity = NSUserActivity(activityType: "com.AppCoda.SiriSortcuts.sayHi") / / 1
        activity.title = "Say Hi" / / 2
        activity.userInfo = ["speech" : "hi"] / / 3
        activity.isEligibleForSearch = true / / 4
        activity.isEligibleForPrediction = true / / 5
        activity.persistentIdentifier = NSUserActivityPersistentIdentifier(rawValue: "com.AppCoda.SiriSortcuts.sayHi") / / 6
        view.userActivity = activity / / 7
        activity.becomeCurrent() / / 8
    }
Copy the code

Let’s take a look at what this code does.

  • On the first line, we create an instance of NSUserActivity and assign the identity we defined in the info.plist file to activityType.

  • In the second line, we define the title of the Activity. (Will be used in Settings center and Spotlight search. If you’re not familiar with how NSUserActivity and spotlight search indexes work, I recommend you read our other tutorials on this topic.)

  • On the third line, we add a userInfo dictionary. According to Apple, the userInfo dictionary contains application-related status information needed to continue activity on another device.

  • Next, we set the.isELIGibleForSearch parameter to true and enable isEligibleForPrediction on the next line. These two properties allow iOS to provide searches and suggestions for our NSUserActivity on the device.

  • Next, we’ll persistentIdentifier attribute is set to NSUserActivityPersistentIdentifier instances, this example with construction with the first line the same identifier.

  • Finally, we assign the activity instance created above to the userActivity property of the view, and call the becomeCurrent() method to activate our activity.

Let’s create another method called sayHi() and paste the following code. This code creates a UIAlertController to display the message.

public func sayHi(a) {
        let alert = UIAlertController(title: "Hi There!", message: "Hey there! Glad to see you got this working!", preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
        self.present(alert, animated: true, completion: nil)}Copy the code

The above is a simple way to illustrate how Siri Shortcuts work. Also note that this is a public function, because we need to use it outside the scope of the view controller.

The public Activity

Now that you’ve set up the basic functionality in ViewController.swift, Switch to the AppDelegate. Swift file and add the application (_ : continueUserActivity: restorationHandler) method, as shown below.

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) - >Bool {
    letviewController = window? .rootViewControlleras! ViewController
  viewController.sayHi()
  return true
}
Copy the code

The above code exposes our newly created Activity in the application delegate method and allows Siri to invoke the application for that Activity.

Now let’s try it! Navigate to the Settings app and select Siri. You should see a new shortcut called “Say Hi”. Click the + button to add it, and then follow the on-screen prompts to create a custom voice phrase to create this shortcut.

Now you can call up Siri and say your phrase and experience Shortcut!

conclusion

As you can see, it’s easy to implement the power of Siri Shortcuts with NSUserActivity in a project. In this tutorial, I created a basic application, and you can apply these techniques to your own applications as well. There are many more scenarios for Siri Shortcuts and I’m sure developers will find more innovative and unique ways to use this new technology.

This article is translated by SwiftGG translation team and has been authorized to be translated by the authors. Please visit swift.gg for the latest articles.