Fix: Display Image in iOS Push Notification on Lock Screen

Fix: Display Image in iOS Push Notification on Lock Screen
Quick answer: To display an image in an iOS push notification on the lock screen, add a UNNotificationAttachment with a local file URL to your notification content. For remote notifications, include “mutable-content”: 1 and a matching category in the APNs payload. For custom expanded UI, implement a UNNotificationContentExtension.

Why this happens

iOS 10 introduced the UserNotifications framework, which changed how notifications are presented. By default, a remote or local notification shows only text (title, body) and an app icon. Images do not appear unless you explicitly attach them or provide a custom content extension. The system supports two distinct paths:

  • UNNotificationAttachment – a lightweight way to show a thumbnail on the right side of the banner or lock-screen alert. Works for both local and remote notifications.
  • UNNotificationContentExtension – a full custom view controller that appears when the user expands the notification (3D Touch / long press). Requires a notification category, an Info.plist entry, and the mutable-content flag for remote pushes.

Choosing the wrong path adds unnecessary complexity. If you only need a picture next to the text, the attachment API is sufficient and does not require a content extension target.

How to fix it

1. Add an image with UNNotificationAttachment (simplest, works for local and remote)

Create a UNMutableNotificationContent instance, build a UNNotificationAttachment from a local file URL, and assign it to the content’s attachments array. The file must already exist on disk (bundle resource, cached download, or generated file).

import UserNotifications

func scheduleLocalNotificationWithImage() {
    let content = UNMutableNotificationContent()
    content.title = "New Photo"
    content.body = "Tap to view"
    content.categoryIdentifier = "imageCategory" // optional, but useful for actions

    // Local file URL – must be a file:// URL ending in .png, .jpg, .gif, etc.
    guard let imageURL = Bundle.main.url(forResource: "sample", withExtension: "png") else { return }

    do {
        let attachment = try UNNotificationAttachment(identifier: "photo", url: imageURL, options: nil)
        content.attachments = [attachment]
    } catch {
        print("Attachment error: \(error)")
    }

    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
    UNUserNotificationCenter.current().add(request) { error in
        if let error = error { print("Schedule error: \(error)") }
    }
}

Key points
* The URL must be a file URL (file://). Remote HTTPS URLs are not accepted directly – download the image first, write to a temporary file, then attach that file.
* Supported types: image (PNG, JPEG, GIF), audio, and movie. Maximum size is ~50 MB (system-enforced).
* No category or content extension is required for the thumbnail to appear.

2. Send the required APNs payload for remote notifications

For a remote push to show the attachment, the JSON payload must contain two fields inside aps:

{
  "aps": {
    "alert": {
      "title": "New Photo",
      "body": "Tap to view"
    },
    "mutable-content": 1,
    "category": "imageCategory"
  },
  "image-url": "https://example.com/photo.jpg"
}
  • "mutable-content": 1 tells iOS to wake your Notification Service Extension (if you have one) so you can download the image and attach it before display.
  • "category": "imageCategory" must match a UNNotificationCategory you registered and (optionally) the UNNotificationExtensionCategory in your content extension’s Info.plist.
  • Custom keys like "image-url" are passed to your service extension via request.content.userInfo.

3. Download and attach in a Notification Service Extension (remote only)

Create a Notification Service Extension target. In its didReceive(_:withContentHandler:):

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,
              let imageURLString = request.content.userInfo["image-url"] as? String,
              let imageURL = URL(string: imageURLString) else {
            contentHandler(bestAttemptContent ?? request.content)
            return
        }

        // Download to a temporary file
        let task = URLSession.shared.downloadTask(with: imageURL) { localURL, _, error in
            guard let localURL = localURL, error == nil else {
                contentHandler(bestAttemptContent)
                return
            }

            // Move to a permanent temp location with correct extension
            let tmpDir = FileManager.default.temporaryDirectory
            let fileName = UUID().uuidString + ".png"
            let destURL = tmpDir.appendingPathComponent(fileName)
            try? FileManager.default.moveItem(at: localURL, to: destURL)

            do {
                let attachment = try UNNotificationAttachment(identifier: "remote-image", url: destURL, options: nil)
                bestAttemptContent.attachments = [attachment]
            } catch {
                print("Attachment creation failed: \(error)")
            }
            contentHandler(bestAttemptContent)
        }
        task.resume()
    }

    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}

The extension has ~30 seconds to finish. Always call the content handler in serviceExtensionTimeWillExpire() as a fallback.

4. Implement a custom UI with UNNotificationContentExtension (optional)

If you need a fully custom expanded view (e.g., carousel, buttons, dynamic layout), add a Notification Content Extension target.

  1. Register a category:
let category = UNNotificationCategory(identifier: "imageCategory",
                                      actions: [],
                                      intentIdentifiers: [],
                                      options: [.customDismissAction])
UNUserNotificationCenter.current().setNotificationCategories([category])
  1. In the extension’s Info.plist, set UNNotificationExtensionCategory to "imageCategory".
  2. Design the view controller in the extension’s storyboard or code. The system passes the notification via didReceive(_:).
  3. The same mutable-content: 1 and category in the APNs payload route the notification to this extension when expanded.

Use this only when the attachment thumbnail is not enough. It adds a separate target, increases app size, and requires the user to long-press/3D Touch to see the custom UI.

How to prevent it

  • Test on device – Simulator behavior can differ (especially for content extensions).
  • Validate file URLs – Attachments reject non-file URLs and unsupported extensions.
  • Handle missing images gracefully – If the download fails, send the notification without an attachment rather than dropping the push.
  • Reuse categories – Define category identifiers in a shared constants file used by the app, service extension, and content extension.
  • Respect size limits – Large attachments delay delivery and may be stripped by APNs.

FAQ

Does UNNotificationAttachment work on the lock screen without a content extension?

Yes. The thumbnail appears on the right side of the lock-screen alert and in the notification banner. No content extension or category registration is required for this basic display.

Why doesn’t my remote notification show the image even though I added mutable-content?

mutable-content: 1 only wakes the Notification Service Extension. You must implement that extension, download the image, create a UNNotificationAttachment from the local file, and call the content handler with the modified content. The payload alone does not attach the image.

Can I use a remote HTTPS URL directly in UNNotificationAttachment?

No. UNNotificationAttachment requires a local file:// URL. Download the remote resource first (typically in the Notification Service Extension for remote pushes), write it to a temporary file, then create the attachment from that file.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.