UNNotificationServiceExtension didReceive未触发,图片推送通知失效
iOS带图推送无法触发UNNotificationServiceExtension的问题排查
以下是代码中存在的几个关键问题及修复方案:
1. Payload中mutable_content类型错误
你的sendNotificationWithAttachment函数里,mutable_content被设置为字符串'true',但FCM要求该字段必须是布尔值true。字符串类型的配置不会触发UNNotificationServiceExtension,这是导致didReceive方法不执行的核心原因。
修复后的Payload代码:
function sendNotificationWithAttachment(topic, title, bodyText, imageUrl) { const payload = { notification: { title: title, body: bodyText, badge: '1', mutable_content: true, // 改为布尔值类型 }, data: { type: 'MESSAGE', fromUserId: title, attachmentUrl: imageUrl } } admin.messaging().sendToTopic(topic, payload) }
2. Payload与Extension的图片URL键名不匹配
Payload的data字段用attachmentUrl存储图片地址,但Extension代码里尝试从userInfo["image"]取值,键名完全不匹配。即使Extension触发,也无法获取到图片URL,导致图片无法显示。
修复Extension代码中的键名:
// 原代码 guard let imageURLString = bestAttemptContent.userInfo["image"] as? String else { contentHandler(bestAttemptContent) return } // 修改为 guard let imageURLString = bestAttemptContent.userInfo["attachmentUrl"] as? String else { contentHandler(bestAttemptContent) return }
额外注意事项
- iOS 13及以上版本要求推送中的图片URL必须使用HTTPS协议,HTTP地址会被系统拦截,导致图片下载失败。如果你的图片资源仍用HTTP,需尽快切换到HTTPS。
- 确认UNNotificationServiceExtension的Target配置正确:Bundle ID需为主APP Bundle ID加上自定义后缀(如
.notification-service),且签名配置与主APP保持一致。 - 测试带图推送时,需确保APP处于后台或完全杀死状态,前台推送的
willPresent方法处理逻辑不会触发Service Extension。
内容的提问来源于stack exchange,提问作者zak
相关产品推荐
相关产品推荐

