Search code examples
iosswiftdeep-linking

iOS Deep link callbacks not working when the app is closed


I'm using a deep linking in my application and using this code in my SceneDelegate to segue to a view controller.

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
  for context in URLContexts {
    print("url: \(context.url.absoluteURL)")
    print("scheme: \(context.url.scheme ?? "")")
    print("host: \(context.url.host ?? "")")
    print("path: \(context.url.path)")
    print("query: \(context.url.query ?? "")")
    print("components: \(context.url.pathComponents)")
  }
    window?.rootViewController?.performSegue(withIdentifier: "splashToCreateNewPassword", sender: nil)
}

It's working perfectly when app is already open in the background, but when user closes the app, it wont work. it just opens the first screen of the app.


Solution

  • You can get URL from this delegate func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
            if let userActivity = connectionOptions.userActivities.first {
                if let incomingURL = userActivity.webpageURL {
                    window?.rootViewController?.performSegue(withIdentifier: "splashToCreateNewPassword", sender: nil)
                }
            }
        }
    

    For those, who use only AppDelegate

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            
            if let userActDic = launchOptions?[UIApplication.LaunchOptionsKey.userActivityDictionary] as? [String: Any],
               let userActivity  = userActDic["UIApplicationLaunchOptionsUserActivityKey"] as? NSUserActivity {
                // Do with user activity
            }
        }