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

Firebase通知技术问询:后台接收通知及点击打开链接实现

Hey,我来帮你搞定Firebase推送通知打开指定链接的需求,分前台、后台两种场景给你梳理清楚:

实现Firebase推送通知打开指定链接

一、需求拆解

  • 接收Firebase推送时,自动打开预先指定的链接
  • 应用处于后台时,通过didReceiveRemoteNotification方法处理推送并触发链接跳转

二、完整实现步骤

1. 先搞定基础配置(必做前提)

确保你已经完成这些准备工作:

  • 把Firebase SDK集成到iOS项目里
  • 在Apple开发者后台配置好推送证书,同步到Firebase控制台
  • 项目的Info.plist里开启remote-notification的后台模式(UIBackgroundModes数组添加该字段)

2. 后台状态下的推送处理(对应你提供的代码片段)

完善你给出的方法,加上链接解析和跳转逻辑:

func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) { 
    // 打印推送内容方便调试
    print("Push notification received: \(data)") 
    // 清除应用角标
    application.applicationIconBadgeNumber = 0 

    // 解析推送中的目标链接(这里假设链接放在alert的"link"字段,或者根节点的"deep_link"字段)
    guard let aps = data["aps"] as? NSDictionary,
          let alertDict = aps["alert"] as? NSDictionary,
          let targetURLString = alertDict["link"] as? String ?? data["deep_link"] as? String,
          let targetURL = URL(string: targetURLString) else {
        print("推送里没找到有效链接哦")
        return
    }

    // 后台状态下打开链接,确保在主线程执行
    if application.applicationState == .background {
        if UIApplication.shared.canOpenURL(targetURL) {
            DispatchQueue.main.async {
                UIApplication.shared.open(targetURL, options: [:], completionHandler: nil)
            }
        }
    }
}

3. 前台状态下的推送处理

如果应用在前台,Firebase默认不会弹出系统通知,得自己处理通知展示和链接跳转:

import UserNotifications

// 先在App启动时注册通知权限
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // 初始化Firebase
    FirebaseApp.configure()

    // 请求用户允许推送权限
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
        if granted {
            DispatchQueue.main.async {
                application.registerForRemoteNotifications()
            }
        }
    }
    UNUserNotificationCenter.current().delegate = self
    return true
}

// 扩展AppDelegate实现通知代理
extension AppDelegate: UNUserNotificationCenterDelegate {
    // 前台收到推送时,先弹出系统通知,再处理链接跳转
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // 显示系统通知(弹窗、角标、声音)
        completionHandler([.alert, .badge, .sound])
        
        // 解析推送里的链接
        let userInfo = notification.request.content.userInfo
        guard let targetURLString = userInfo["deep_link"] as? String ?? (userInfo["aps"] as? NSDictionary)?["alert"] as? NSDictionary?["link"] as? String,
              let targetURL = URL(string: targetURLString) else {
            return
        }
        
        // 打开链接
        if UIApplication.shared.canOpenURL(targetURL) {
            UIApplication.shared.open(targetURL, options: [:], completionHandler: nil)
        }
    }
}

4. Firebase推送消息的格式要求

发送推送时,要在payload里携带自定义链接字段,比如两种写法都可以:

// 写法1:链接放在alert字段里
{
  "aps": {
    "alert": {
      "title": "新消息提醒",
      "body": "点击查看详情",
      "link": "https://your-target-url.com"
    },
    "badge": 1,
    "sound": "default"
  }
}

// 写法2:链接放在根节点(推荐,避免alert字段的格式限制)
{
  "aps": {
    "alert": {
      "title": "新消息提醒",
      "body": "点击查看详情"
    },
    "badge": 1,
    "sound": "default"
  },
  "deep_link": "https://your-target-url.com"
}

三、重要注意事项

  • 如果要打开自定义scheme的链接(比如yourapp://detail),得在Info.plist的LSApplicationQueriesSchemes数组里添加对应的scheme
  • 后台状态下触发didReceiveRemoteNotification,需要推送payload里加上"content-available": 1字段,否则可能无法触发方法
  • 测试时可以用Firebase控制台的「Cloud Messaging」发送测试推送,直接填写自定义字段就行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:21:17