iOS项目不使用Branch SDK获取appID及触发open url方案咨询
iOS Swift 原生处理深度链接获取参数(移除Branch方案)
核心实现逻辑
移除Branch后,根据App的生命周期场景分别处理深度链接跳转即可获取拼接的参数:
- 冷启动场景:App未在后台存活,用户点击链接唤起App,需要在
didFinishLaunchingWithOptions方法中从启动参数中提取URL - 热启动场景:App在后台存活,用户点击链接唤起App,直接从URL回调方法中提取URL
无SceneDelegate(iOS12及更早版本/项目未启用Scene)的实现
- 冷启动参数提取,在
AppDelegate的didFinishLaunchingWithOptions方法中添加如下代码:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 处理冷启动时的URL Scheme跳转 if let url = launchOptions?[.url] as? URL { let appID = getQueryParameter(from: url, paramName: "appID") // 后续处理appID逻辑 } return true }
- 热启动参数提取,实现
AppDelegate的openURL回调方法:
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { let appID = getQueryParameter(from: url, paramName: "appID") // 后续处理appID逻辑 return true }
- 通用URL参数解析工具方法:
func getQueryParameter(from url: URL, paramName: String) -> String? { let components = URLComponents(url: url, resolvingAgainstBaseURL: true) return components?.queryItems?.first { $0.name == paramName }?.value }
启用SceneDelegate(iOS13及以上版本)的实现
如果你的项目启用了Scene,URL回调不会触发AppDelegate的openURL方法,这是该方法不触发的最常见原因,需要在SceneDelegate中实现对应回调:
- 冷启动处理:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // 处理冷启动URL跳转 if let urlContext = connectionOptions.urlContexts.first { let url = urlContext.url let appID = getQueryParameter(from: url, paramName: "appID") // 后续处理appID逻辑 } // 处理冷启动通用链接跳转 if let userActivity = connectionOptions.userActivities.first, userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL { let appID = getQueryParameter(from: url, paramName: "appID") // 后续处理appID逻辑 } }
- 热启动URL Scheme处理:
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { guard let url = URLContexts.first?.url else { return } let appID = getQueryParameter(from: url, paramName: "appID") // 后续处理appID逻辑 }
- 热启动通用链接处理:
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL else { return } let appID = getQueryParameter(from: url, paramName: "appID") // 后续处理appID逻辑 }
openURL方法不触发的排查项
- 确认
Info.plist中URL Types配置正确:URL Schemes只填写前缀即可,不需要加://,比如你的跳转链接是myapp://?appID=123,只需要填写myapp - 确认跳转的链接格式正确,前缀和配置的URL Scheme完全匹配,无拼写错误
- 如果你使用的是
Universal Link(https开头的深度链接),需要确认已配置好苹果开发者后台的关联域名以及项目的Associated Domains权限,回调走通用链接对应方法,不会走openURL
内容的提问来源于stack exchange,提问作者HariKarthick
相关产品推荐
相关产品推荐

