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

如何在iOS的FCM推送通知中渲染HTML与富文本

在iOS FCM推送中渲染HTML富文本的解决方案

iOS系统默认的通知展示(横幅、通知中心)不支持直接解析HTML内容,仅能显示纯文本。你之前尝试直接转换aps.alert.body失败,是因为FCM传递的aps.alert.body会自动转义HTML标签,导致无法正确解析。要实现富文本(含图片、链接等)通知,需通过**自定义通知内容扩展(Notification Content Extension)**来处理,具体步骤如下:

1. 配置FCM推送Payload

在推送Payload中必须添加mutable-content: 1字段,告诉iOS系统需要调用自定义扩展处理内容。同时将HTML富文本放在自定义字段中(不要放在aps.alert.body内),示例Payload:

{
  "aps": {
    "alert": {
      "title": "富文本通知",
      "body": "查看详情" // 系统默认展示的纯文本内容
    },
    "mutable-content": 1
  },
  "custom_html": "<p><img src='图片URL' /> 这是包含图片和<a href='链接地址'>可点击链接</a>的富文本内容</p>"
}

2. 创建Notification Content Extension

在Xcode中为项目添加新Target:

  • 选择File > New > Target,找到Notification Content Extension模板
  • 配置扩展的Bundle ID(需与主App的Bundle ID关联,例如主App为com.your.app,扩展可设为com.your.app.notification-extension)
  • 激活扩展Scheme,确保能正常编译

3. 在扩展中解析并渲染HTML

打开扩展的NotificationViewController.swift,修改didReceive(_:)方法,解析自定义字段中的HTML并生成富文本:

import UIKit
import UserNotifications
import UserNotificationsUI

class NotificationViewController: UIViewController, UNNotificationContentExtension {

    override func viewDidLoad() {
        super.viewDidLoad()
        // 初始化富文本展示控件
        let textView = UITextView(frame: view.bounds)
        textView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        textView.isEditable = false
        textView.isScrollEnabled = true
        textView.dataDetectorTypes = .link // 自动识别链接
        textView.delegate = self
        view.addSubview(textView)
    }
    
    override func didReceive(_ notification: UNNotification) {
        let content = notification.request.content
        guard let htmlString = content.userInfo["custom_html"] as? String else { return }
        
        // 将HTML转换为NSAttributedString
        let htmlData = htmlString.data(using: .utf8)!
        let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ]
        
        do {
            let attributedText = try NSAttributedString(data: htmlData, options: options, documentAttributes: nil)
            if let textView = view.subviews.first as? UITextView {
                textView.attributedText = attributedText
            }
        } catch {
            print("HTML解析失败: \(error.localizedDescription)")
        }
    }
}

// 处理链接点击逻辑
extension NotificationViewController: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        extensionContext?.open(URL, completionHandler: nil)
        return false
    }
}

4. 注意事项

  • 图片加载优化:若HTML中的图片无法直接显示,可使用SDWebImage等第三方库,将图片URL转换为NSAttributedString附件后再解析。
  • 权限配置:若需在扩展中打开外部链接,需在扩展的Info.plist中添加LSApplicationQueriesSchemes,配置允许跳转的URL Scheme。
  • UI适配:需根据通知的展示样式(横幅/展开式)调整自定义UI布局,确保在不同设备上显示正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:10:37