iOS Swift中如何为Firebase推送通知添加操作按钮?
嘿,我来帮你搞定这个需求!你要实现的是通知展开后的操作按钮,也就是当用户滑动通知点击「查看」(或者直接展开通知)时显示的交互按钮。下面分Android和iOS两个平台,给你基于Firebase Cloud Messaging(FCM)的具体实现步骤:
Android 端实现方案
Android的通知动作按钮可以通过三种方式配置,覆盖快速可视化配置和自定义开发场景:
方式1:Firebase控制台快速配置
- 登录Firebase控制台进入你的项目,选择「Cloud Messaging」
- 创建新通知时,滚动到「高级选项」→「动作」
- 点击「添加动作」,填写按钮的「标题」(比如“查看详情”)和「意图」(格式为
包名/类名,例如com.your.app/DetailActivity,指定要打开的页面) - 发送通知后,用户展开通知就能看到按钮,点击后直接触发对应的页面跳转
方式2:通过FCM API/Admin SDK自定义
如果是服务器端批量发送通知,可以在消息payload里指定动作配置,以Java Admin SDK为例:
// 构建带动作按钮的通知消息 Message message = Message.builder() .setNotification(Notification.builder() .setTitle("新消息提醒") .setBody("点击查看详情") .build()) // 用data字段传递动作按钮的配置信息 .putData("actions", "[{\"action\":\"VIEW_DETAILS\",\"title\":\"查看详情\"},{\"action\":\"MARK_READ\",\"title\":\"标记已读\"}]") .setToken("目标设备的推送Token") .build(); // 发送消息 FirebaseMessaging.getInstance().send(message);
然后在App里注册BroadcastReceiver处理动作逻辑:
public class NotificationActionReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); switch (action) { case "VIEW_DETAILS": // 打开详情页面 Intent detailIntent = new Intent(context, DetailActivity.class); detailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(detailIntent); break; case "MARK_READ": // 执行标记已读的业务逻辑 Toast.makeText(context, "已标记为已读", Toast.LENGTH_SHORT).show(); break; } } }
方式3:在FirebaseMessagingService里手动构建通知
如果需要更高的自定义灵活性,可以在FirebaseMessagingService的onMessageReceived方法里直接创建带按钮的通知:
@Override public void onMessageReceived(RemoteMessage remoteMessage) { // 创建跳转详情页的PendingIntent Intent viewIntent = new Intent(this, DetailActivity.class); PendingIntent pendingIntentView = PendingIntent.getActivity(this, 0, viewIntent, PendingIntent.FLAG_IMMUTABLE); // 创建标记已读的PendingIntent Intent readIntent = new Intent(this, NotificationActionReceiver.class); readIntent.setAction("MARK_READ"); PendingIntent pendingIntentRead = PendingIntent.getBroadcast(this, 1, readIntent, PendingIntent.FLAG_IMMUTABLE); // 构建带动作按钮的通知 NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "YOUR_CHANNEL_ID") .setSmallIcon(R.drawable.ic_notification) .setContentTitle(remoteMessage.getNotification().getTitle()) .setContentText(remoteMessage.getNotification().getBody()) .setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody())) .setPriority(NotificationCompat.PRIORITY_DEFAULT) // 添加两个动作按钮 .addAction(R.drawable.ic_view, "查看详情", pendingIntentView) .addAction(R.drawable.ic_read, "标记已读", pendingIntentRead); // 发送通知 NotificationManagerCompat.from(this).notify(1001, builder.build()); }
iOS 端实现方案
iOS需要通过通知类别(UNNotificationCategory)和动作(UNNotificationAction)来配置扩展按钮,步骤如下:
1. 注册通知类别和动作
在App的启动逻辑里(比如AppDelegate的didFinishLaunchingWithOptions)完成通知权限申请和类别注册:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 请求通知权限 UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in if granted { DispatchQueue.main.async { application.registerForRemoteNotifications() } } } // 创建动作按钮 let viewAction = UNNotificationAction( identifier: "VIEW_DETAILS", title: "查看详情", options: [.foreground] // 点击后将App切换到前台 ) let markReadAction = UNNotificationAction( identifier: "MARK_READ", title: "标记已读", options: [] ) // 创建通知类别 let notificationCategory = UNNotificationCategory( identifier: "CUSTOM_NOTIFICATION_CATEGORY", actions: [viewAction, markReadAction], intentIdentifiers: [], options: [] ) // 注册类别到系统 UNUserNotificationCenter.current().setNotificationCategories([notificationCategory]) return true }
2. 发送FCM消息时关联类别
通过Admin SDK发送消息时,需要在APNS payload里指定对应的类别ID:
ApnsConfig apnsConfig = ApnsConfig.builder() .putHeader("apns-priority", "10") .setAps(Aps.builder() .setCategory("CUSTOM_NOTIFICATION_CATEGORY") // 关联注册的通知类别 .setAlert(ApsAlert.builder() .setTitle("新消息提醒") .setBody("点击查看详情") .build()) .build()) .build(); Message message = Message.builder() .setApnsConfig(apnsConfig) .setToken("目标设备的推送Token") .build(); FirebaseMessaging.getInstance().send(message);
3. 处理动作按钮的回调
在AppDelegate里实现动作按钮的点击逻辑:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { switch response.actionIdentifier { case "VIEW_DETAILS": // 打开详情页面 if let rootVC = UIApplication.shared.connectedScenes.first?.windows.first?.rootViewController { let detailVC = DetailViewController() rootVC.present(detailVC, animated: true) } case "MARK_READ": // 执行标记已读的业务逻辑 print("通知已标记为已读") default: break } completionHandler() }
关键注意事项
- Android 8.0及以上必须先创建通知渠道,动作按钮属于渠道配置的一部分,需确保渠道已正确创建
- 动作按钮数量有限制:Android最多3个,iOS最多4个
- iOS需确保已正确申请通知权限,并且App已完成远程通知注册
- 如果用Firebase控制台发送iOS通知,需在「高级选项」→「APNS」里指定「类别」为你注册的类别ID
内容的提问来源于stack exchange,提问作者Pranit
相关产品推荐
相关产品推荐

