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

iOS:如何通过自定义用户通知展示HTML格式的远程通知内容

如何在iOS自定义通知中展示HTML格式内容

嘿,这个问题我熟!默认的APNs推送通知并不支持直接解析HTML标签,要展示你收到的那种带<a>、<b>这类标签的通知内容,咱们得借助UNNotificationServiceExtension(通知服务扩展)来实现自定义处理,具体步骤如下:

1. 给项目添加通知服务扩展

首先得在Xcode里给你的项目新增一个通知服务扩展目标:

  • 打开Xcode,点击菜单栏的 File > New > Target
  • 在弹出的窗口里选择 Notification Service Extension,点击Next
  • 给扩展起个名字(比如HTMLNotificationExtension),然后点击Finish
  • 当Xcode询问是否激活这个扩展时,选择Activate

2. 编写HTML解析与通知内容替换代码

打开刚创建的扩展里的NotificationService.swift文件,替换默认代码为以下内容:

import UserNotifications

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        guard let bestAttemptContent = bestAttemptContent else {
            contentHandler(request.content)
            return
        }
        
        // 从推送内容里提取HTML格式的文本
        let htmlContent = bestAttemptContent.body
        
        // 将HTML字符串转换为富文本
        guard let htmlData = htmlContent.data(using: .utf8) else {
            contentHandler(bestAttemptContent)
            return
        }
        
        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)
            // 替换通知的正文为解析后的富文本
            bestAttemptContent.attributedBody = attributedText
        } catch {
            // 如果转换失败,就保留原文本内容
            print("HTML解析失败: \(error.localizedDescription)")
        }
        
        // 交付处理后的通知内容
        contentHandler(bestAttemptContent)
    }

    override func serviceExtensionTimeWillExpire() {
        // 当扩展处理超时,直接返回原始内容
        if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}

3. 配置正确的推送Payload

要让通知服务扩展生效,你的推送Payload必须包含mutable-content: 1字段,这样APNs才会把通知交给扩展处理。比如你提供的示例Payload要改成这样:

{
  "aps": {
    "mutable-content": 1,
    "alert": {
      "title": "自定义HTML通知",
      "body": "<a>this is a tag</a><br/><b>this text will bold out</b>"
    }
  }
}

一些注意事项

  • iOS对HTML标签的支持有限,常用的<b>、<i>、<br>、<p>、<a>这些都能解析,但像<div>、<span>这类复杂标签可能不会完全生效。
  • 如果你的HTML内容是放在自定义字段里(比如userInfo里的html_alert),那在代码里要改成从request.content.userInfo["html_alert"]提取内容,而不是bestAttemptContent.body。
  • 对于<a>标签,默认点击通知只会打开你的App,要实现点击链接跳转的话,还得在App里处理通知的响应事件,提取链接并打开Safari或者内部页面。

内容的提问来源于stack exchange,提问作者Thiều Quang Cường

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:19:04