iOS自定义URL唤起App后App Delegate回调未触发问题
针对你遇到的application(_:open:options:)回调未触发的情况,可按以下步骤排查和解决:
清理SceneDelegate残留影响
即使移除了Info.plist中的Application Scene Manifest,如果项目里还保留着SceneDelegate.swift文件,iOS 13+系统可能还是会优先走Scene相关的URL回调(scene(_:openURLContexts:))。你可以直接删除SceneDelegate.swift文件;如果需要保留该文件,要么在其中实现URL处理逻辑,要么确保系统将路由指向AppDelegate的回调。核对回调函数签名
仔细检查函数的参数、返回值和命名是否完全正确,哪怕细微的拼写错误都会导致回调失效。正确的函数签名应为:func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { print("Received URL: \(url)") // 这里添加URL处理逻辑 return true }注意返回值必须是
Bool类型,参数名和类型不能有偏差。验证Info.plist的URL Scheme配置
检查CFBundleURLTypes的结构是否正确,确保Scheme值和测试时使用的URL完全匹配(Scheme区分大小写):<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>你的自定义Scheme</string> </array> <key>CFBundleURLName</key> <string>com.yourapp.bundleid</string> </dict> </array>确认AppDelegate为正确的应用代理
检查项目配置细节:- 确保Info.plist中未指定
Principal Class,若指定则需指向你的AppDelegate类; - 检查项目的
Main Interface设置,若使用Storyboard,确认其关联的AppDelegate无误; - 若用纯代码创建窗口,需在
AppDelegate中正确初始化并设置window:var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = YourRootViewController() window?.makeKeyAndVisible() return true }
- 确保Info.plist中未指定
强制iOS 13+使用AppDelegate逻辑
若上述步骤无效,可在AppDelegate中添加Scene配置方法,强制系统跳过SceneDelegate:func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { let config = UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) config.delegateClass = nil return config }排查第三方库拦截
检查项目中是否集成了登录、分享类等涉及URL跳转的第三方SDK,部分库会接管URL处理流程,导致AppDelegate的回调无法触发。可暂时移除第三方库测试,确认是否是其导致的问题。
内容的提问来源于stack exchange,提问作者Nishtha Verma

