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

冷暖自知 提交于 2019-12-04 11:21:14

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!