1

What I am trying to achieve

Handle custom url type when app is launched or not launched.

What I did

  • Define a custom url type
  • Implement the .onOpenURL in my View like this

(only to debug, I observe this custom event so that I can check when it occurs)

 .onOpenURL(perform: { url in
        if (url.host! == "web" && url.pathComponents.count > 1) {
            NotificationCenter.default.post(name: .receivedIncomingURL, object: nil)
        }
    })

The problem and what I tried

The app does not react on the custom url when it is not launched. According to the docs [1], I had to implement a method in the AppDelegate which I did like this (event tried to kill the app with fatalError() but the code block is not executed.

func application(_ application: UIApplication,
                 open url: URL,
                 options: [UIApplicationOpenURLOptionsKey : Any] = [:] ) -> Bool {
      NotificationCenter.default.post(name: .receivedIncomingURL, object: nil)
      // event tried fatalError() here.
}

Questions

The documentation also says, that whenever you opted to Scene (UIKit Scene), you have to use the SceneDelegate which my App does not have. My SwiftUI @main App contains the definition var body: some Scene { // } - does that mean, that I opted to Scene in the way the documentation means it? So I have to implement a SceneDelegate in the SwiftUI App?!? Or is there another way to react on the custom url in a closed app?

[1] https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app

McGo
  • 3,792
  • 2
  • 13
  • 18

1 Answers1

3

So I finally came up with a solution. It is not needed to implement a SceneDelegate, the .onOpenUrl modifier works like a charm but:

  • It can be used on every view and on the App itself.
  • Since I used it on my main view everything worked when the app was loaded
  • What I forgot to mention is, that I have a custom "splash view" with a video animation. This is loaded only once when the app starts and since neither the app itself nor the splashscreen implemented .onOpenUrl, my app does not recognize incoming urls when it is started for the first time
  • I now use the same snippet not on the main view but on the app and everything works great.

Sometime thinking about the problem 10289390123 times helps..

McGo
  • 3,792
  • 2
  • 13
  • 18