应用程序关闭时打开 URL 方案中的内容

Lun*_*ebb 2 url-scheme ios appdelegate swift uiscenedelegate

我的问题

我正在我的应用程序中实现 URL 方案,当应用程序位于前台或后台时,它们总体工作正常。但是,我注意到,当它完全关闭并且另一个应用程序尝试使用我的 URL(例如app:page?image=1)访问通常可以工作的内容时,它只会打开该应用程序,但内容永远不会被捕获。

我的方法

我已经在 AppDelegate 和 SceneDelegate 方法中设置了代码

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:])
Run Code Online (Sandbox Code Playgroud)

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
Run Code Online (Sandbox Code Playgroud)

期望的行为

当应用程序处于后台、前台或关闭时它会打开

实际行为

它仅在前台或后台时打开

Mut*_*awe 5

为了处理传入的 URL,我们只需在scene(_:willConnectTo:options:)scene(_:openURLContexts:)委托方法中调用此函数即可:

如果应用程序关闭:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let _ = (scene as? UIWindowScene) else { return }
    
    
    // Since this function isn't exclusively called to handle URLs we're not going to prematurely return if no URL is present.
    if let url = connectionOptions.urlContexts.first?.url {
        handleURL(url: url)
    }
}
Run Code Online (Sandbox Code Playgroud)

如果应用程序在后台或前台

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    // Get the first URL out of the URLContexts set. If it does not exist, abort handling the passed URLs and exit this method.
    guard let url = URLContexts.first?.url else {
        return NSLog("No URL passed to open the app")
    }


    
    handleURL(url: url)
}
Run Code Online (Sandbox Code Playgroud)

您可以返回以下文章,了解有关场景委托和 URL 方案的更多信息:iOS 中的自定义 URL 方案