DEV Community

himaratsu
himaratsu

Posted on

How to use Siri Shortcuts in your app

Introduction

Siri shortcut is one of the biggest update in iOS 12.
If you said to Siri about your task, Siri responds with your apps installed.
SiriKit is published in iOS 12, which make developers enable to adapt Siri to their apps.

Recently, my app had adaptive SiriKit. I introduce my code.

For using Siri Shortcut, We have tw ways. NSUserActivity, or Intents.
Today I introduce NSUserActivity because it is very simple.

How to use Siri Shortcuts

1. Regist Siri Shortcut

My code:

import UIKit
import Intents  // 1. import Intents framework

class CheckinViewController: UIViewController {

   override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        // 2. register Siri shortcut action when user did some of action
        userActivity = NSUserActivity.checkinActivity
    }
}


extension NSUserActivity {

    public static let checkinType = "com.example.checkin"

    public static var checkinActivity: NSUserActivity {
        let userActivity = NSUserActivity(activityType: checkinType)

        userActivity.isEligibleForSearch = true

        // 3. set `isEligibleForPrediction` true
        //    you should set recommend phrase to `suggestedInvocationPhrase`
        if #available(iOS 12.0, *) {
            userActivity.isEligibleForPrediction = true
            userActivity.suggestedInvocationPhrase = "Check in"
        }
        userActivity.title = "Check in to the nearest station"

        return userActivity
    }
}

This code is mostly same to Apple sample code.
When user action something, you register it to iOS with NSUserActivity.

2. Use NSUserActivity

Once registering Siri, user can set up at Settings app > Siri shortcuts section.

Handling user action by Siri, you implemented delegate method.

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {

        if userActivity.activityType == NSUserActivity.checkinType {
            // Handle Siri Action Here
            return true
        }

        return false
    }

And write definition in your info.plist.

<key>NSUserActivityTypes</key>
<array>
    <string>com.example.checkin</string>
</array>

Recap

In this article, I wrote how to use Siri Shortcut in your app with my actual code.
The way of using NSUserActivity is very simple and easy.

Hope this article helps anyone!

———

Top comments (0)