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

如何为Firebase推送通知(APNs)添加自定义操作按钮?

为Firebase APNs推送添加“保留/关闭”动作按钮

这类带操作按钮的通知是自定义通知动作,并非APNs默认自带,需要客户端配置通知分类+推送Payload指定分类两步完成,具体步骤如下:

一、iOS客户端配置(以Swift为例)

你需要在App中创建通知动作和分类,并注册到系统通知中心:

  1. 导入UserNotifications框架,编写配置方法:
import UserNotifications

func setupNotificationCategories() {
    // 创建"保留"动作,指定唯一标识和显示标题
    let keepAction = UNNotificationAction(identifier: "ACTION_KEEP",
                                          title: "保留",
                                          options: [])
    
    // 创建"关闭"动作,使用破坏性样式(红色文字)
    let dismissAction = UNNotificationAction(identifier: "ACTION_DISMISS",
                                             title: "关闭",
                                             options: .destructive)
    
    // 创建通知分类,绑定动作列表,指定唯一分类ID
    let calendarCategory = UNNotificationCategory(identifier: "CALENDAR_NOTIFICATION_CATEGORY",
                                                  actions: [keepAction, dismissAction],
                                                  intentIdentifiers: [],
                                                  options: [])
    
    // 将分类注册到系统通知中心
    UNUserNotificationCenter.current().setNotificationCategories([calendarCategory])
}
  1. 在App启动时调用该方法,比如在AppDelegate的application(_:didFinishLaunchingWithOptions:)中:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // 其他初始化代码...
    setupNotificationCategories()
    return true
}

二、Firebase推送Payload配置

发送推送时,必须在Payload中指定对应的分类ID,通知才会显示动作按钮:

方式1:Firebase控制台发送

  1. 进入推送编辑页面,点击高级选项
  2. 在自定义数据中添加键category,值设置为你客户端配置的分类ID(比如CALENDAR_NOTIFICATION_CATEGORY)
  3. 完成其他设置后发送推送

方式2:Firebase Cloud Messaging API发送

在请求的apns.payload.aps字段中添加category属性:

{
  "apns": {
    "payload": {
      "aps": {
        "alert": {
          "title": "你的通知标题",
          "body": "你的通知内容"
        },
        "category": "CALENDAR_NOTIFICATION_CATEGORY"
      }
    }
  },
  "token": "目标设备的推送令牌"
}

注意事项

  • 分类ID必须客户端和推送Payload完全一致(大小写敏感),否则按钮不会显示
  • 确保用户已授予App通知权限,动作按钮仅在用户允许通知的前提下显示
  • 动作按钮仅在锁屏、通知中心的通知中显示,后台静默通知不会展示按钮

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:30:52