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

iOS Firebase推送通知:后台自定义处理Base64编码内容

Firebase后台通知自定义处理方案(Base64内容解码)

这个问题我之前帮不少开发者解决过——核心在于要绕开系统直接接管通知的逻辑,把消息控制权拿到自己手里,分Android和iOS两种场景给你说清楚:

Android平台

Firebase在Android上的通知分为通知消息和数据消息两种:

  • 如果服务器发的是通知消息,App后台时系统会直接展示通知,你完全没机会拦截修改;
  • 所以必须让服务器发送纯数据消息(或者通知+数据的混合消息,但后台时还是优先走系统通知,所以推荐纯数据),这样不管前台后台,消息都会落到你自定义的FirebaseMessagingService里。

实现步骤:

  1. 创建FirebaseMessagingService子类,重写onMessageReceived方法:
class MyFirebaseMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        // 从消息中获取Base64编码的内容
        val encodedContent = remoteMessage.data["content"] ?: return
        
        // 解码Base64
        val decodedBytes = Base64.decode(encodedContent, Base64.DEFAULT)
        val decodedContent = String(decodedBytes, Charsets.UTF_8)
        
        // 自定义通知内容(标题、内容都可以自己定义)
        val notificationBuilder = NotificationCompat.Builder(this, "CHANNEL_ID")
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("自定义标题")
            .setContentText(decodedContent)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        
        // 展示通知
        with(NotificationManagerCompat.from(this)) {
            notify(System.currentTimeMillis().toInt(), notificationBuilder.build())
        }
    }
}
  1. 在AndroidManifest.xml中注册这个Service:
<service
    android:name=".MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
  1. 提醒服务器:发送消息时不要包含notification字段,只传data字段,比如:
{
  "to": "DEVICE_TOKEN",
  "data": {
    "content": "Base64编码的字符串"
  }
}

iOS平台

iOS后台处理推送需要依赖静默推送能力,核心是让服务器推送时带上content-available: 1字段,这样App在后台会被唤醒一小段时间,让你有机会处理消息。

实现步骤:

  1. 开启后台推送权限:在Xcode的项目Capabilities中,打开Background Modes,勾选Remote notifications。
  2. 在AppDelegate中实现didReceiveRemoteNotification:fetchCompletionHandler:方法:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // 获取Base64编码内容
    guard let encodedContent = userInfo["content"] as? String else {
        completionHandler(.failed)
        return
    }
    
    // 解码Base64
    guard let decodedData = Data(base64Encoded: encodedContent),
          let decodedContent = String(data: decodedData, encoding: .utf8) else {
        completionHandler(.failed)
        return
    }
    
    // 自定义通知并展示
    let content = UNMutableNotificationContent()
    content.title = "自定义标题"
    content.body = decodedContent
    content.sound = UNNotificationSound.default
    
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
    UNUserNotificationCenter.current().add(request) { error in
        if let error = error {
            print("通知创建失败:\(error)")
            completionHandler(.failed)
        } else {
            completionHandler(.newData)
        }
    }
}
  1. 提醒服务器:推送消息时必须包含content-available: 1,并且不要包含alert字段(否则系统会直接展示默认通知),示例APNs payload:
{
  "aps": {
    "content-available": 1
  },
  "content": "Base64编码的字符串"
}

关键注意事项

  • 不管Android还是iOS,必须让服务器配合发送正确格式的消息,否则系统会直接接管通知,你没有修改机会;
  • Base64解码时要注意编码格式(比如是否带换行、URL安全的Base64等),避免解码失败;
  • Android需要创建通知渠道(Android 8.0+),否则通知无法展示;
  • iOS测试后台推送时,不要用Xcode的模拟器,最好用真机测试,并且App要真正处于后台状态(不是挂起)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:14:50