App 关闭时从 URL Scheme 中打开内容

Opening content from URL Scheme when App is closed

我的问题

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

我的方法

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

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:])

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {

期望的行为

当应用程序在后台、前台或关闭时打开

实际行为

仅在前台或后台打开

由于您的应用目前 not running,它将使用这些启动选项启动。也就是说,这些选项将改为传递给 willFinishLaunchingWithOptions: / didFinishLaunchingWithOptions:。将您的代码添加到这些方法之一。

有关详细信息,请阅读有关如何 Respond to the Launch of Your App, or, more specifically Determine Why Your App Was Launched 的文档。

编辑:

正如下面@paulw11 所评论的,场景委托的工作方式不同,必须单独处理。

然而,在Respond to Scene-Based Life-Cycle Events部分,最后一点是:

In addition to scene-related events, you must also respond to the launch of your app using your UIApplicationDelegate object. For information about what to do at app launch, see Responding to the Launch of Your App

所以我假设,我们仍然需要在 willdidFinishLaunchingWithOptions / didFinishLaunchingWithOptions 中处理启动。

为了处理传入的 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)
    }
}

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

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)
}

有关场景委托和URL方案的更多信息,您可以返回以下文章:Custom URL Schemes in iOS