8 min read
Notification service extensions: images, actions, and their real limits
Attaching images and actions to notifications with a service extension, and the time and memory limits that extension runs under.
On this page8
A notification service extension is documented as the place to attach an image to a push. In practice it is a separate process with a hard deadline, a memory ceiling you will not see in the profiler you are used to, and a failure mode that delivers the notification anyway, minus the parts it was supposed to add.
That is why the bug report reads "the image shows up sometimes". The push arrived, the extension started, something in it gave up quietly, and iOS delivered the original payload. There is no crash line to find.
1. What runs, and for how long
The system launches your extension only when the payload contains mutable-content: 1. Without it, nothing is invoked and no amount of code in the extension target helps.
Once launched, didReceive(_:withContentHandler:) has about 30 seconds. If you have not called the content handler at that point, serviceExtensionTimeWillExpire() runs, and whatever is in that callback is delivered. If neither path calls the handler, iOS delivers the untouched payload.
Thirty seconds sounds generous until you spend it on the wrong things. Two sequential network calls, a cold DNS lookup, and a signed URL that needs refreshing will take it all. Budget for one request.
class NotificationService: UNNotificationServiceExtension {
private var contentHandler: ((UNNotificationContent) -> Void)?
private var attempt: UNMutableNotificationContent?
override func didReceive(
_ request: UNNotificationRequest,
withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void
) {
self.contentHandler = contentHandler
self.attempt = request.content.mutableCopy() as? UNMutableNotificationContent
guard let raw = request.content.userInfo["image-url"] as? String,
let url = URL(string: raw) else {
finish(with: request.content)
return
}
URLSession.shared.downloadTask(with: url) { localURL, response, _ in
if let localURL,
let type = response?.mimeType,
let attachment = try? UNNotificationAttachment(
identifier: "hero",
url: localURL,
options: [UNNotificationAttachmentOptionsTypeHintKey: type]
) {
self.attempt?.attachments = [attachment]
}
self.finish()
}.resume()
}
override func serviceExtensionTimeWillExpire() {
finish()
}
private func finish(with fallback: UNNotificationContent? = nil) {
guard let handler = contentHandler else { return }
contentHandler = nil
handler(attempt ?? fallback ?? UNMutableNotificationContent())
}
}The contentHandler = nil guard matters. The expiry path and the completion path can both fire, and calling the handler twice is a crash you will only ever see on slow networks.
2. Attachments are files, not URLs
UNNotificationAttachment takes a file URL on the local disk. It cannot fetch anything, and it rejects https URLs. That is the whole reason downloadTask is used above: it produces a temporary file you can hand over, and URLSession deletes it later.
Three details cause most of the remaining failures:
- Pass
UNNotificationAttachmentOptionsTypeHintKeywith a real UTI. Without a hint, the system infers the type from the file extension, and CDN URLs that end in a query string have no extension to read. - The system copies the file into its own container, so you do not need to keep your copy.
- The identifier is the deduplication key. Reusing
"hero"across notifications is correct here; using a random UUID per send gives you duplicate attachments when the same push is retried.
Attachment file size is capped at about 10 MB. A photo that passes on a fast connection and fails on the mobile network it was designed for is usually just over that line.
3. Memory is the limit that bites
The extension process gets far less memory than your app, roughly 24 MB. A 12-megapixel JPEG decoded into memory is about 48 MB of RGBA before any processing. The extension gets killed, iOS delivers the original notification, and the image is missing with nothing in the logs.
The fix is to never decode the full image. Downscale with ImageIO, which streams and produces a thumbnail without materialising the source:
func thumbnail(from url: URL, maxPixel: CGFloat) -> URL? {
guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil }
let options: [CFString: Any] = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceThumbnailMaxPixelSize: maxPixel
]
guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else {
return nil
}
let out = FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).jpg")
guard let destination = CGImageDestinationCreateWithURL(out as CFURL, UTType.jpeg.identifier as CFString, 1, nil) else {
return nil
}
CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: 0.8] as CFDictionary)
return CGImageDestinationFinalize(destination) ? out : nil
}A max pixel size of 1024 covers a notification banner on every current device and keeps the decoded bitmap around 4 MB. Pass that file to UNNotificationAttachment instead of the download.
4. The payload is 4 KB, and the URL lives in it
APNs payloads cap at 4 KB. A signed CDN URL with a long token can eat 500 bytes on its own, and if you attach two of them the encryption and alert text start competing for room.
Keep the URL short and unsigned, and put the access control in the path or an identifier instead of a query signature. If the media genuinely needs a token, store the media id in the payload and resolve the URL inside the extension in the one request you have. Two round trips (metadata, then the image) is the pattern that produces occasional blank notifications on slow networks and looks intermittent in reports.
One more thing about the payload: the extension modifies the content, and the alert text has already been assembled by the server. If the extension is going to replace the body with a localized or personalised version, send something sane as the fallback, because that original text is what gets delivered whenever the extension fails.
5. Actions belong to the app, not the extension
Actions are declared with a category the app registers, and they are handled by the app delegate. The extension never sees them. Attempting to do action work in didReceive because "the extension is already running" leads to handlers that fire twice on the next launch.
Register categories at launch, not when the first push arrives. A notification delivered before the category exists renders with no buttons, and the category does not retroactively apply to it.
let accept = UNNotificationAction(identifier: "order.accept", title: "Accept")
let decline = UNNotificationAction(
identifier: "order.decline",
title: "Decline",
options: [.destructive, .authenticationRequired]
)
let reply = UNTextInputNotificationAction(
identifier: "order.reply",
title: "Reply",
textInputButtonTitle: "Send",
textInputPlaceholder: "Message"
)
let category = UNNotificationCategory(
identifier: "ORDER",
actions: [accept, decline, reply],
intentIdentifiers: [],
options: [.customDismissAction]
)
UNUserNotificationCenter.current().setNotificationCategories([category])Four actions is the practical maximum the interface shows in a long look; anything beyond that is invisible. .foreground opens the app before running the handler, which is right for anything that needs a screen. Without it, iOS wakes the app in the background, and you have a short window to write to your store and call the completion handler. Doing a network request there works, doing three does not.
Handling is a switch on the action identifier, with UNNotificationDefaultActionIdentifier covering the plain tap:
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse
) async {
let info = response.notification.request.content.userInfo
switch response.actionIdentifier {
case "order.accept":
await orders.accept(id: info["order-id"] as? String)
case UNNotificationDefaultActionIdentifier:
router.open(info)
default:
break
}
}6. The extension is a different process
Standard UserDefaults, the app's keychain items unless configured as a shared group, and any in-memory state are gone. Anything the extension needs has to come through an App Group container or a network call.
In practice that means the auth token for the media CDN lives in a shared keychain access group or a shared defaults suite, and there is a refresh path for when it has expired by the time the push arrives. Notifications often arrive days after a session was established, which is exactly when the token you cached in testing has gone stale.
7. Test the paths that fail, and use the simulator loop
xcrun simctl push gives a two-second loop, which is the difference between testing five payload variants and testing one:
xcrun simctl push booted com.example.app payload.jsonDrop mutable-content and confirm the notification still arrives without the image. Point the URL at a 404. Point it at a 20 MB file. Add a five-second sleep in the download path and watch the expiry branch produce a usable notification. Those four checks cover most of what reaches production.
The simulator does not enforce the memory ceiling or the timing the way a device does, so run the large-image case on hardware before signing off. Attach the debugger by selecting the extension scheme and choosing "Ask on Launch", then trigger a real push at the user's device token; os_log from the extension appears in Console under your subsystem.
8. Use it when the attachment carries the message
The extension adds a second process that Apple can kill for reasons it does not report, plus a network dependency inside a 30-second window. That cost is worth paying when the image or the decrypted content is the point of the notification: a message preview, a delivery photo, a boarding pass.
For decorative artwork on a marketing push, a plain alert renders faster, never fails, and looks the same to most people reading it on a lock screen. Ship the text version first, measure whether anyone opens the notifications with media in them, and add the extension when the data says the image matters.
The same extension also earns its place for end-to-end encrypted payloads, where it decrypts content before the system shows it. That is a real requirement rather than an aesthetic one, and it justifies the target on its own.