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

iOS富通知UNNotificationAttachment视频缩略图全灰问题

iOS富通知MP4附件缩略图灰度问题解决方案

问题现象

  • 通知payload携带MP4下载地址,端上通过urlSession下载文件存储到本地后,通知展开状态下视频可正常播放,但折叠/列表态的缩略图仅显示灰色调,包括Nest在内的多款第三方应用均存在相同表现,该问题早在2年前就有相关反馈。

问题复现代码

NSData* data = //urlSessionDownloadTask返回的数据            
NSString *key = [url lastPathComponent];
NSURL *tempDirectory = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSURL *fileURL = [tempDirectory URLByAppendingPathComponent:key];

NSError *diskWriteError;
const BOOL writeToDiskSucceeded = [data writeToURL:fileURL options:NSDataWritingAtomic error:&diskWriteError];
if (!writeToDiskSucceeded) {
    completion(nil, @"writing error");
} else {
    NSError *attachmentError;
    UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:@"media-id"
                                                                                        URL:fileURL
                                                                                    options:@{
        UNNotificationAttachmentOptionsThumbnailTimeKey : @(1)
    } error:&attachmentError];
    // 后续修改mutable content添加附件逻辑
}

问题原因

该问题不是业务代码逻辑错误,是iOS系统UNNotificationAttachment自动生成缩略图的固有bug:当MP4文件采用H.265(HEVC)编码、或者色彩元数据缺失/不匹配时,系统内置的截帧流程会丢失色彩通道,最终输出纯灰度的缩略图。

修复方案

  • 端上手动生成缩略图,绕过系统自动截帧逻辑
    不依赖系统的自动截帧能力,MP4下载完成后,先通过AVAssetImageGenerator手动截取对应时间点的帧,生成标准sRGB格式的图片存储到本地,创建附件时通过UNNotificationAttachmentOptionsThumbnailURLKey参数绑定自定义缩略图即可,核心实现代码:
// 基于本地MP4文件初始化AVAsset
AVURLAsset *videoAsset = [AVURLAsset assetWithURL:fileURL];
AVAssetImageGenerator *frameGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:videoAsset];
frameGenerator.appliesPreferredTrackTransform = YES;
// 截取视频第1秒位置的帧
CMTime captureTime = CMTimeMake(1, 1);
CGImageRef frameCGImage = [frameGenerator copyCGImageAtTime:captureTime actualTime:nil error:nil];
UIImage *customThumb = [UIImage imageWithCGImage:frameCGImage];
CGImageRelease(frameCGImage);

// 将自定义缩略图写入临时目录
NSURL *thumbSaveURL = [tempDirectory URLByAppendingPathComponent:@"notification_thumb.jpg"];
[UIImageJPEGRepresentation(customThumb, 0.9) writeToURL:thumbSaveURL atomically:YES];

// 创建通知附件时绑定自定义缩略图
UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:@"media-id"
                                                                                        URL:fileURL
                                                                                    options:@{
    UNNotificationAttachmentOptionsThumbnailURLKey: thumbSaveURL
} error:&attachmentError];
  • 服务端统一MP4输出规范
    如果端上不想新增截帧逻辑,可以让服务端输出推送用MP4时统一采用H.264(AVC)编码,同时写入标准sRGB色彩元数据,系统自动截帧时就不会出现色彩丢失问题。

问题效果参考

通知缩略图灰度异常效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 19:45:55