iOS 13+: Can't get a notification userInfo when opening a deeplink

459 Views Asked by At

I have faced the problem that I can't solve with Notifications and Deeplinks.

When opening a deeplink UIApplication used to send a UIApplication.didFinishLaunchingNotification with userInfo that contained UIApplicationLaunchOptionsURLKey with the URL that was opened.

So we could subscribe to it like this:

NotificationCenter.default.addObserver(forName: UIApplication.didFinishLaunchingNotification, object: nil, queue: nil) { (notification) in
    print(notification.userInfo) // prints UIApplicationLaunchOptionsURLKey: url_that_opened_the_app
}

Now, after iOS 13 it does not happen: userInfo is nil.

So the question is: is there a way to receive a notification from Notification Center when app opens a deeplink?

*Thoughts: * I think that it is caused by the fact that UISceneDelegate is in charge of opening deeplinks now, which is confirmed by the fact that if we remove the SceneDelegate, we can get our userInfo back. I tried to find if any of SceneDelegate notifications provide us with such information, but they don't: both didActivateNotification and willConnectNotification give nothing.

1

There are 1 best solutions below

3
Rajan Maheshwari On

Yes, you can find the same with SceneDelegate as well.
Here is a Sample I made.

Once you launch your app from deep links, you will receive connectionOptions in

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
}

You can get your URL as follows:

if let context = connectionOptions.urlContexts.first as? UIOpenURLContext {
    print(context.url.absoluteString)
}

So your function will look like:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    
    guard let _ = (scene as? UIWindowScene) else { return }
    
    if let context = connectionOptions.urlContexts.first {
        print(context.url.absoluteString)
        //Here you can pass this URL to your notification and perform your logic.
    }
}

DeepLink I tested was:
deeplinks://mycustomDeepLink

Also I changed the scheme to Wait for the Executable to Launch to check the initial launch thing from deep links. enter image description here

Note: Sometimes debugger doesn't work for whatsoever reason. So, in my sample, I added an alert view in the ViewController.