iosswiftios-universal-links

How to retrieve the Universal Link URL clicked inside my app


I am looking for a way to retrieve the universal link full URL inside my swift app.

Here is my apple-app-site-association:

$ curl https://app.mycompany.io/.well-known/apple-app-site-association
{
  "applinks": {
      "details": [
           {
             "appIDs": [ "ABCD1234.io.mybundle" ],
             "paths": [
                "*"
             ],
             "components": [
               {"/": "/*"}
             ]
           }
       ]
   }
}

Here is the main classes for my app:

struct MyApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    @ObservedObject var model = MyAppModel()
    
    var body: some Scene {
        return WindowGroup() {
           ...
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {

        // Here I initialize my app     
        return true
    }
    
    func application(_ application: UIApplication, continue userActivity: NSUserActicity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
      // Here I thought I could grab the universal link clicked to act accordingly
      return true
    }
}

My problem is that the second function in my AppDelegate class never gets called. Not when I launch the app from the home screen, not when I launch the app when clicking in a link (mail or Safari) nor when I put the app back in the focus after it being in the background when clicking a link.

I need a way to extract the link that was clicked to know what my app is supposed to do:

Edit 1

I succeeded in the first goal up there (Getting the URL on app startup) with the following code:

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        for x in options.userActivities {
            if x.activityType == NSUserActivityTypeBrowsingWeb {
                if let url = x.webpageURL {
                    handleDeepLink(url)
                }
            }
        }
        return UISceneConfiguration()
    }

Still searching how to get the URL when the app is brought back from background on a universal link click.


Solution

  • To detect the URL clicked that brings the app forward I had to add an onOpenURL handler to the body of my App:

        var body: some Scene {
            WindowGroup {
                ZStack {
                  ...
                }.onOpenURL { url in
                  // Do something in the URL
                }
            }
        }