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

如何在iOS中通过Firebase Cloud Messaging推送通知发送Deep Link

iOS FCM推送触发Deep Link(前台/后台通用)

一、分状态处理逻辑

1. 应用前台状态

利用onMessageReceived(或Messaging代理方法)直接解析推送参数并执行跳转:

// 用UIApplication的通知回调
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if application.applicationState == .active {
        if let deepLink = userInfo["deep_link"] as? String {
            // 调用你已实现的Deep Link跳转方法
            handleDeepLink(urlString: deepLink)
        }
    }
    completionHandler(.noData)
}

// 或用Messaging代理方法
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    if let deepLink = remoteMessage.appData["deep_link"] as? String {
        handleDeepLink(urlString: deepLink)
    }
}

2. 应用后台/未启动状态

这类状态下,用户点击通知栏消息才会触发App唤醒/启动,需在启动回调中处理:

// App首次启动时的处理
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    if let remoteNotification = launchOptions?[.remoteNotification] as? [AnyHashable: Any],
       let deepLink = remoteNotification["deep_link"] as? String {
        // 延迟跳转确保App初始化完成
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            self.handleDeepLink(urlString: deepLink)
        }
    }
    return true
}

// 后台唤醒时的处理
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if application.applicationState == .inactive || application.applicationState == .background {
        if let deepLink = userInfo["deep_link"] as? String {
            handleDeepLink(urlString: deepLink)
        }
    }
    completionHandler(.noData)
}

二、Firebase Console传递Deep Link的正确操作

很多开发者踩坑是因为参数位置错误,正确步骤:

  • 进入Firebase Console的Cloud Messaging模块,新建通知
  • 填写标题、内容后,下拉到Additional options
  • 点击Add an item,Key填自定义参数名(比如deep_link),Value填完整Deep Link地址(如yourapp://product/123)
  • 注意:不要使用Notification标签页的Deep link输入框(该字段用于关联App Store/网页跳转,不支持自定义内部Deep Link)

三、关键注意事项

  • 确保你的handleDeepLink方法能稳定解析并执行跳转,兼容外部URL和内部参数调用场景
  • 后台唤醒跳转时,需等待UI初始化完成再执行,避免页面加载异常
  • 测试后台状态时,需将App退至后台(或杀掉进程),点击通知验证跳转逻辑
  • 若使用静默通知(无通知栏展示),需开启后台推送权限,并将content-available设为1,此时前后台都会触发通知回调

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:30:30