How to handle URL callbacks with new SwiftUI @main startup?

In the old SwiftUI app initialization there was UIApplicationDelegate and UIWindowSceneDelegate.

I was handling a URL callback in the SceneDelegate using the method:

Code Block
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>)

However in the new app initialization there is no SceneDelegate, nor an appropriate property like there is UIApplicationDelegateAdaptor for UIApplicationDelegate

I tried using the method but it is not called.

Code Block
func application( _ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:] ) -> Bool

So my question is, how do I handle a callback url in the new app setup?


Accepted Reply

You can use the onOpenURL(perform:) view modifier. https://developer.apple.com/documentation/swiftui/outlinesubgroupchildren/onopenurl(perform:)

Code Block
var body: some Scene {
    WindowGroup {
        ContentView()
            .onOpenURL { (url) in
// Handle url here
}
}
}

Replies

You can use the onOpenURL(perform:) view modifier. https://developer.apple.com/documentation/swiftui/outlinesubgroupchildren/onopenurl(perform:)

Code Block
var body: some Scene {
    WindowGroup {
        ContentView()
            .onOpenURL { (url) in
// Handle url here
}
}
}

Can confirm that it works perfectly.

Any view inside the WindowGroup works, I preferred it a bit deeper in my hierarchy attached to the button the triggers the webview for login, so that I'm not importing the library I'm using into the App file.
For some reason this doesn't work for me when I switch to the macOS build. [The documentation][link] lists macOS 11 support on the website (and the docs in Xcode list 10.16), but I'm getting an error that my view "has no member 'onOpenURL'".

[link]: https://developer.apple.com/documentation/swiftui/anyview/onopenurl(perform:)
Post not yet marked as solved Up vote reply of bfad Down vote reply of bfad
@bfad I have also seen this message regarding similar iOS 14 features that run fine on the beta simulators (running iOS 14). The corresponding macOS features, intuitively, will be designed for BigSur. You rightly point out 10.16 < 11 and I am guessing that for this reason, there is an incompatibility and hence the reason the macOS cannot find the member onOpenURL. I hope that helps.