How can I open my SwiftUI app and perform a function using NSUseractivity from within Siri Intent Extension?

倖福魔咒の 提交于 2019-12-03 08:39:27

Like you already commented you can use func scene(_ scene: UIScene, continue userActivity: NSUserActivity) to continue the NSUserActivity when the app is still in the background.

However when the app is closed you can implement let userActvity = connectionOptions.userActivities.first inside the scene(_:willConnectTo:options:) method inside the SceneDelegate to access the activity the user wants to continue.

Just adding this piece of code to the standard implementation of this method would look like this:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

    // Use a UIHostingController as window root view controller
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: ContentView())
        self.window = window
        window.makeKeyAndVisible()

        //Standard implementation until here
        if let userActvity = connectionOptions.userActivities.first {
            if let intent = userActivity.interaction?.intent as? YourIntent {
                print(“do something”)
            }
        }
    }
}

This works for Siri Intents with Swift 5 Xcode 11.

For Handoff though the .userActivities should not be used as the documentation says, instead the associated delegate methods will be called (scene(_:continue:)):

This property does not contain user activity objects related to Handoff. At connection time, UIKit delivers only the type of a Handoff interaction in the handoffUserActivityType property. Later, it calls additional methods of the delegate to deliver the NSUserActivity object itself.

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