如何在iOS上修改推送通知图标?基于React-native与notifee/react-native
iOS端使用notifee/react-native实现推送通知自定义头像(仿Slack)
iOS系统推送通知机制和Android不同,无法直接替换通知小图标,但可以通过添加媒体附件的方式实现类似Slack的头像展示效果——把发送者头像作为通知媒体内容显示在通知栏里。结合notifee/react-native,具体实现分两种场景:
一、本地通知场景
本地通知可直接在React Native层处理头像下载和附件添加:
- 先将发送者头像图片下载到设备本地(可使用
react-native-fs或其他文件操作库) - 在notifee的
Notification配置中,通过attachments字段传入本地图片路径作为附件
示例代码:
import notifee from '@notifee/react-native'; import RNFS from 'react-native-fs'; async function showNotificationWithAvatar(senderAvatarUrl, title, body) { // 下载头像到临时目录 const localAvatarPath = `${RNFS.TemporaryDirectoryPath}/sender_avatar.jpg`; await RNFS.downloadFile({ fromUrl: senderAvatarUrl, toFile: localAvatarPath, }).promise; // 创建带头像的通知 await notifee.displayNotification({ title, body, ios: { attachments: [ { url: `file://${localAvatarPath}`, thumbnailHidden: false, // 显示头像缩略图 }, ], }, }); }
二、远程通知场景
远程通知需要配合APNs推送和iOS原生Notification Service Extension处理,步骤如下:
- 配置APNs推送:推送Payload必须包含
mutable-content: 1,告知iOS系统需要调用扩展处理通知 - 创建Notification Service Extension:在Xcode中给React Native项目添加新的Notification Service Extension目标
- 在Extension代码中,下载发送者头像并添加为通知附件
推送Payload示例(后端发送)
{ "aps": { "alert": { "title": "新消息", "body": "你有一条未读消息" }, "mutable-content": 1, "sender-avatar-url": "https://example.com/user-avatar.jpg" // 自定义字段传递头像URL } }
Notification Service Extension代码(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 content = bestAttemptContent else { contentHandler(request.content) return } // 从自定义字段获取头像URL guard let avatarUrlString = content.userInfo["sender-avatar-url"] as? String, let avatarUrl = URL(string: avatarUrlString) else { contentHandler(content) return } // 下载头像并添加为附件 URLSession.shared.downloadTask(with: avatarUrl) { [weak self] tempUrl, response, error in guard let self = self, let tempUrl = tempUrl, let attachment = try? UNNotificationAttachment(identifier: "avatar", url: tempUrl, options: nil) else { contentHandler(content) return } content.attachments = [attachment] self.contentHandler?(content) }.resume() } override func serviceExtensionTimeWillExpire() { // 超时 fallback,直接返回原始通知内容 if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } }
三、关键注意事项
- iOS版本要求:媒体附件功能仅支持iOS 10及以上版本
- 图片限制:推荐使用JPG/PNG格式,图片大小不超过10MB;远程图片下载需控制在系统给Extension的超时时间内(约30秒)
- 权限配置:本地图片场景需确保已申请文件访问权限;Extension需配置网络权限以下载远程头像
- 基础配置:已按照notifee官方文档完成iOS端推送基础配置(如添加推送证书、配置
Info.plist等)
内容的提问来源于stack exchange,提问作者yusooho
相关产品推荐
相关产品推荐

