You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS Swift中application(_:open url:options:)方法完全不触发

问题根因

项目启用了iOS 13+的SceneDelegate生命周期,此时系统不会触发AppDelegate中实现的application(_:open:options:)回调,所有外部URL唤起事件只会派发到SceneDelegate的相关方法。你把深链跳转逻辑写在了不会被调用的AppDelegate方法中,仅在SceneDelegate的URL回调里做了打印,自然无法触发预期的页面跳转。

解决步骤
  • 迁移深链处理逻辑到SceneDelegate
    将URL解析、页面跳转的逻辑移到scene(_:openURLContexts:)方法中,注意从回调的URLContexts集合中取出实际URL对象,参考实现:
    func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        guard let url = URLContexts.first?.url else { return }
        handleDeepLink(url: url)
    }
    
  • 补全冷启动场景的深链处理
    当目标应用处于完全杀进程的冷启动状态被深链唤起时,不会走openURLContexts回调,URL参数会包含在scene(_:willConnectTo:options:)的连接参数里,需要在这里做兼容处理:
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let windowScene = (scene as? UIWindowScene) else { return }
        window = UIWindow(windowScene: windowScene)
        // 保留原有根控制器初始化逻辑
        let mainVC = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
        window?.rootViewController = mainVC
        window?.makeKeyAndVisible()
        
        // 处理冷启动传入的深链
        if let urlContext = connectionOptions.urlContexts.first {
            handleDeepLink(url: urlContext.url)
        }
    }
    
  • 抽离公共深链处理方法,避免重复代码,统一处理跳转逻辑:
    private func handleDeepLink(url: URL) {
        let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)
        let host = urlComponents?.host ?? ""
        guard host == "accessPage" else { return }
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        guard let targetVC = storyboard.instantiateViewController(withIdentifier: "jsonVC") as? JSONViewController else { return }
        // 确保在主线程执行UI操作
        DispatchQueue.main.async {
            self.window?.rootViewController = targetVC
        }
    }
    
  • 校验基础配置
    • 确认发起跳转的源应用Info.plist中,已将second加入LSApplicationQueriesSchemes白名单,否则canOpenURL会返回false,无法正常唤起目标应用
    • 确认目标应用的URL Scheme配置正确,CFBundleURLSchemes下确实存在second项,无拼写错误

内容的提问来源于stack exchange,提问作者senanindigo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 06:54:30