onOpenURL not called for single-window Mac OS application

Hi,

I'm developing an app using SwiftUI for both iOS and Mac OS and use onOpenURL to handle external links. However, this doesn't seem to work after switching to a single window app on Mac OS.

This code works:

WindowGroup {
    Text("Hi").onOpenURL { url in
        print("Open URL", url)
    }
}

But this doesn't:

Window("My App", id: "my_app") {
    Text("Hi").onOpenURL { url in
        print("Open URL", url)
    }
}

Anyone knows a workaround? Thanks!

Answered by CrescentFlare in 786930022

Eventually solved it using a custom app delegate:

final class AppDelegate: NSObject, NSApplicationDelegate {
    var openUrlCallback: ((_ url: URL) -> Void)?

    func application(_ application: NSApplication, open urls: [URL]) {
        for url in urls {
            openUrlCallback?(url)
        }
    }
}

struct MyApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        Window("My App", id: "my_app") {
            Text("Hi").onAppear {
                appDelegate.openUrlCallback = { url in
                    print("Open URL", url)
                }
            }
        }
    }
}
Accepted Answer

Eventually solved it using a custom app delegate:

final class AppDelegate: NSObject, NSApplicationDelegate {
    var openUrlCallback: ((_ url: URL) -> Void)?

    func application(_ application: NSApplication, open urls: [URL]) {
        for url in urls {
            openUrlCallback?(url)
        }
    }
}

struct MyApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        Window("My App", id: "my_app") {
            Text("Hi").onAppear {
                appDelegate.openUrlCallback = { url in
                    print("Open URL", url)
                }
            }
        }
    }
}
onOpenURL not called for single-window Mac OS application
 
 
Q