首页 > 解决方案 > iOS 13+:打开深层链接时无法获得通知 userInfo

问题描述

我遇到了通知和深层链接无法解决的问题。

打开深度链接时,UIApplication 用于发送包含UIApplication.didFinishLaunchingNotification打开的 URL 的内容。userInfoUIApplicationLaunchOptionsURLKey

所以我们可以像这样订阅它:

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

现在,在 iOS 13 之后它不会发生:userInfonil.

所以问题是:当应用打开深层链接时,有没有办法从通知中心接收通知?

*想法: * 我认为这是由UISceneDelegate现在负责打开深度链接的事实引起的,如果我们删除 SceneDelegate,我们可以取回我们的 userInfo,这证实了这一点。我试图找出是否有任何 SceneDelegate 通知为我们提供了此类信息,但它们没有:两者都didActivateNotification没有willConnectNotification提供。

标签: iosiphonedeep-linkingnsnotificationcenternsnotifications

解决方案


是的,你也可以找到相同的SceneDelegate
这是我制作的样品。

connectionOptions从深层链接启动应用后,您将收到

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

您可以按如下方式获取您的网址:

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

所以你的函数看起来像:

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 是:
deeplinks://mycustomDeepLink

此外,我将方案更改为Wait for the Executable to Launch从深层链接检查初始启动内容。 在此处输入图像描述

注意:有时调试器出于某种原因无法正常工作。因此,在我的示例中,我在ViewController.


推荐阅读