1

我的问题

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

我的方法

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

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

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

期望的行为

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

实际行为

它仅在前台或后台打开

4

2 回答 2

3

scene(_:willConnectTo:options:)要处理传入的 URL,我们只需在委托方法和委托方法中调用此函数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 方案的更多信息:iOS 中的自定义 URL 方案

于 2020-12-15T00:31:10.153 回答
2

由于您的应用当前未运行,它将使用这些启动选项启动。即这些选项将被传递给willFinishLaunchingWithOptions:/ didFinishLaunchingWithOptions:。将您的代码添加到这些方法之一。

有关更多信息,请阅读有关如何响应应用程序启动的文档,或者更具体地说,确定启动应用程序的原因

编辑:

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

但是,在响应基于场景的生命周期事件部分中,最后一点是:

除了与场景相关的事件之外,您还必须使用 UIApplicationDelegate 对象来响应应用程序的启动。有关在应用程序启动时要做什么的信息,请参阅 响应应用程序的启动

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

于 2020-04-29T23:00:35.410 回答