You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何修改iOS推送通知缩略图的图片比例及尺寸?

如何自定义iOS推送通知缩略图的尺寸与宽高比(实现WWDC风格效果)

嘿,我正好研究过这个问题——完全可以自定义iOS推送通知里的缩略图尺寸和宽高比,WWDC展示的那种精致、规整的缩略图效果,其实是利用iOS的UNNotificationAttachment框架特性实现的,下面一步步给你拆解具体怎么做:

先搞懂默认逻辑

iOS默认会自动缩放推送里的媒体附件来适配通知栏,这就是为什么你会觉得效果不符合预期的原因——它不会按你想要的比例裁剪,只会自适应。但通过UNNotificationAttachment的配置选项,我们可以完全掌控缩略图的展示方式。

1. 准备符合要求的媒体素材

首先得确保你的图片/视频满足APNs的基础要求:

  • 图片格式限PNG/JPG,大小不超过10MB(iOS 10+);视频用MOV/MP4,不超过50MB
  • 提前把素材调整到你想要的宽高比(比如WWDC常用的16:9或正方形)会让后续的裁剪更顺畅,当然也可以让系统帮你裁剪

2. 本地通知的自定义缩略图实现

如果是本地触发的通知,直接在代码里创建附件时配置参数就行:

// 先获取本地素材的URL
guard let imageURL = Bundle.main.url(forResource: "wwdc-style-thumb", withExtension: "jpg") else {
    print("找不到素材文件")
    return
}

// 核心:设置缩略图的裁剪模式和展示尺寸
let attachmentOptions = [
    // 裁剪模式:clippingRect会按指定尺寸裁剪,保持比例;scaleToFill是拉伸填充;none是自适应
    UNNotificationAttachmentOptionsThumbnailClippingKey: UNNotificationAttachmentThumbnailClipping.clippingRect.rawValue,
    // 指定缩略图尺寸,这里是16:9比例的示例
    UNNotificationAttachmentOptionsThumbnailSizeKey: NSValue(cgSize: CGSize(width: 300, height: 169))
]

do {
    // 创建通知附件
    let thumbnailAttachment = try UNNotificationAttachment(identifier: "custom-thumb", url: imageURL, options: attachmentOptions)
    
    // 组装通知内容
    let notificationContent = UNMutableNotificationContent()
    notificationContent.title = "WWDC风格通知"
    notificationContent.body = "这是自定义比例的缩略图效果"
    notificationContent.attachments = [thumbnailAttachment]
    
    // 触发通知(5秒后弹出)
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest(identifier: "wwdc-notif", content: notificationContent, trigger: trigger)
    UNUserNotificationCenter.current().add(request)
} catch {
    print("创建附件失败:\(error.localizedDescription)")
}

3. 远程推送的自定义缩略图实现

如果是后台通过APNs发送的远程通知,需要两个关键步骤:

第一步:给APNs的Payload加配置

你的推送Payload必须包含mutable-content: 1,告诉iOS这个通知需要被扩展处理,同时带上媒体文件的URL:

{
    "aps": {
        "alert": {
            "title": "远程WWDC风格通知",
            "body": "自定义缩略图效果"
        },
        "mutable-content": 1
    },
    "media-url": "https://你的服务器地址/wwdc-thumbnail.jpg"
}

第二步:创建Notification Service Extension

这个扩展会在通知到达设备后,下载并处理媒体文件:

  1. 在Xcode里选File > New > Target > Notification Service Extension,跟着向导创建即可
  2. 在自动生成的NotificationService.swift里修改代码:
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,
              let mediaURLString = content.userInfo["media-url"] as? String,
              let mediaURL = URL(string: mediaURLString) else {
            // 处理失败就返回原始通知内容
            contentHandler(request.content)
            return
        }
        
        // 下载媒体文件到临时目录
        let downloadTask = URLSession.shared.downloadTask(with: mediaURL) { [weak self] tempURL, _, error in
            guard let self = self, let tempURL = tempURL else {
                contentHandler(request.content)
                return
            }
            
            let fileManager = FileManager.default
            let tempDir = NSTemporaryDirectory()
            let fileName = mediaURL.lastPathComponent
            let destinationURL = URL(fileURLWithPath: tempDir).appendingPathComponent(fileName)
            
            do {
                // 清理旧文件(如果有的话)
                if fileManager.fileExists(atPath: destinationURL.path) {
                    try fileManager.removeItem(at: destinationURL)
                }
                // 移动下载的文件到临时目录
                try fileManager.moveItem(at: tempURL, to: destinationURL)
                
                // 设置缩略图选项,和本地通知一致
                let attachmentOptions = [
                    UNNotificationAttachmentOptionsThumbnailClippingKey: UNNotificationAttachmentThumbnailClipping.clippingRect.rawValue,
                    UNNotificationAttachmentOptionsThumbnailSizeKey: NSValue(cgSize: CGSize(width: 300, height: 169))
                ]
                
                // 创建附件并添加到通知内容
                let attachment = try UNNotificationAttachment(identifier: "remote-thumb", url: destinationURL, options: attachmentOptions)
                content.attachments = [attachment]
                
                // 交付处理后的通知
                self.contentHandler?(content)
            } catch {
                print("处理远程媒体失败:\(error.localizedDescription)")
                contentHandler(request.content)
            }
        }
        downloadTask.resume()
    }

    override func serviceExtensionTimeWillExpire() {
        // 如果处理超时,返回当前已处理的内容(或者原始内容)
        if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}

4. 复刻WWDC效果的关键技巧

  • 固定宽高比:WWDC的通知缩略图大多用16:9(视频类)或正方形(图片类),把UNNotificationAttachmentOptionsThumbnailSizeKey设为对应比例的尺寸,再配合clippingRect裁剪模式,就能得到规整的效果
  • 用高分辨率素材:不同设备的通知栏尺寸不同,高分辨率素材能保证在大屏幕上也清晰
  • 不要过度压缩:只要控制在iOS的大小限制内,尽量保留素材的清晰度,系统会自动做适配缩放

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

火山引擎 最新活动