在iOS中使用Swift实现推荐深度链接
Hey there! I totally get where you're coming from—Firebase Dynamic Links being deprecated has left a lot of us scrambling for native alternatives, especially for handling referrals when the app isn't even installed yet. Let's break down a solid, SDK-free approach using Apple's native tools and a bit of backend work.
第一步:配置通用链接(Universal Links)
Universal Links are the backbone here—they're reliable, secure, and let you deep link directly into your app without messy custom URL schemes. Here's how to set them up:
在Apple开发者后台配置关联域名
进入你的App ID页面,启用「Associated Domains」,并添加你的域名,格式为applinks:yourapp.com。添加到应用的Entitlements文件
在Xcode中打开项目的Entitlements文件(没有的话新建一个),添加com.apple.developer.associated-domains条目,值为包含applinks:yourapp.com的数组。部署apple-app-site-association文件
创建一个名为apple-app-site-association(不带.json后缀)的JSON文件,结构如下:{ "applinks": { "details": [ { "appIDs": ["你的团队ID.你的App Bundle ID"], "components": [ { "/": "/referral/*", "comment": "匹配所有推荐链接" } ] } ] } }将该文件上传到你的网站根目录或
.well-known子目录,确保通过HTTPS访问,且MIME类型为application/json。
第二步:在应用中处理通用链接
链接配置完成后,需要在应用中处理传入的链接。根据iOS版本不同,分别在SceneDelegate或AppDelegate中实现:
iOS 13+(SceneDelegate):
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL else { return } handleReferralLink(url) }
旧版iOS(AppDelegate):
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL else { return false } handleReferralLink(url) return true }
解析推荐链接的辅助函数:
private func handleReferralLink(_ url: URL) { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true), let referralCode = components.queryItems?.first(where: { $0.name == "code" })?.value else { return } // 存储推荐码到本地,或发送到后端记录 UserDefaults.standard.set(referralCode, forKey: "SavedReferralCode") // 跳转到对应页面,比如推荐奖励页 if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene, let rootVC = windowScene.windows.first?.rootViewController { let rewardVC = RewardViewController(referralCode: referralCode) rootVC.present(rewardVC, animated: true) } }
第三步:处理应用未安装时的推荐场景
这是最棘手的部分,没有第三方SDK的情况下,我们需要一个网页中间页来衔接:
搭建跳转中间页
在https://yourapp.com/referral创建一个简单网页,实现两个逻辑:- 先用JavaScript尝试通过Universal Link打开应用(主流浏览器都支持这个操作);
- 如果应用未安装,自动 fallback 到显示「下载应用」按钮,链接到你的App Store页面。
跟踪未安装状态的推荐
- 用户访问网页时,将推荐码和一个唯一会话标识(比如Cookie生成的会话ID)存储到你的后端;
- 用户安装并首次打开应用时,生成一个持久化的设备UUID(不要在未获得用户同意时使用IDFA),并发送到后端;
- 后端匹配会话标识和设备UUID,将对应的推荐码关联到新用户。
简化的匹配思路:
- 网页端:生成会话ID存入Cookie,同时在后端保存
会话ID → 推荐码的映射; - 应用端:首次启动时生成UUID并存入UserDefaults,发送请求到后端,后端根据用户IP、浏览器信息等匹配会话ID,返回对应的推荐码。
隐私注意事项
- 若使用IDFA等跟踪标识符,必须遵守Apple的ATT框架,获得用户明确同意;
- 不要在未获得用户许可的情况下跟踪用户行为;
- 避免不必要的敏感数据存储。
这一套方案完全基于原生工具,没有依赖第三方SDK,所有逻辑都在你的掌控之中,完美替代即将废弃的Firebase Dynamic Links。
内容来源于stack exchange

