Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Siri Shortcuts to show a specific page in my app?

I want to advanced research Shortcuts technology. So here are some questions:

  • Can Siri shortcuts be used in any type of app? Because of SiriKit only working in tourism, chatting etc.
  • Now using shortcuts. Can I jump to my app showing specific page by Siri?
like image 281
Corbin Avatar asked Dec 10 '22 06:12

Corbin


1 Answers

Can Siri shortcuts be used in any type of app? Because of SiriKit only working in tourism, chatting etc.

Yes, any. They aren't tied to any specific domain. They are custom.

Now using shortcuts. Can I jump to my app showing specific page by Siri?

Yes.


The code below shows the easiest way on how to show a specific page by Siri, it's called "Donating a Shortcut" via NSUserActivity. But you could achieve the same by defining a custom INIntent.

Step 1:

In Info.plist, under NSUserActivityTypes add an activity type string: com.app.viewPage

Step 2:

Create activity:

let viewPageActivityType = "com.app.viewPage"

let viewPageActivity: NSUserActivity = {
    let userActivity = NSUserActivity(activityType: viewPageActivityType)
    userActivity.title = "View Page"
    userActivity.suggestedInvocationPhrase = "View Page"
    userActivity.isEligibleForSearch = true
    userActivity.isEligibleForPrediction = true
    return userActivity
}()

Then add it to your view controller:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        userActivity = viewPageActivity
    }
}

Step 3:

Handle it in UIApplicationDelegate method (this method will get called if a user presses the Shortcut, or activates in from Siri via voice):

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

    if userActivity.activityType == viewPageActivityType {
        print("open the `ViewController` here")
        return true
    }
    return false
}

After the user opens the ViewController once, they may get it suggested in the lock screen and search suggestions. They can also go to Settings -> Siri & Search -> My Shortcuts to define a custom phrase to perform the action using voice.

To debug this, make sure to use a device (not simulator). Then go to Settings -> Developer -> Enable "Display Recent Shortcuts" and "Display Donations on Lock Screen".

There are a lot of great resources on this:

  • Apple Sample Code
  • Introduction to Siri Shortcuts WWDC Session
  • Donating Shortcuts Docs
  • Relevant Shortcuts Docs
like image 109
kgaidis Avatar answered Feb 15 '23 10:02

kgaidis