skip to content

With a UNNotificationServiceExtension, how does an iOS app add a seat-map image to a push, and what happens when the download outlasts its time?

level: seniorimportance: should knowfreq 35%

answer

  1. a separate target that runs before display
  2. mutable-content: 1 plus alert text
  3. an attachment from a local file URL
  4. about 30 seconds, then one last call
  5. no handler call means the original content

basics

~20 s

Add a Notification Service Extension target, send the push with mutable-content: 1 and alert text, download the image in didReceive(_:withContentHandler:), attach it as a UNNotificationAttachment and call the handler; near the roughly 30-second limit, serviceExtensionTimeWillExpire() must deliver fallback content.

solid answer

~50 s

The extension is its own target inside the app bundle. The system runs its `UNNotificationServiceExtension` subclass only for a push whose `aps` has `"mutable-content": 1` and an alert with a title, subtitle or body, and only while alerts are allowed for the app. In `didReceive(_:withContentHandler:)` I read the seat-map URL from a custom key beside `aps`, download it, move the file to a name whose extension tells the type, wrap it in `UNNotificationAttachment(identifier:url:options:)`, set it on a mutable copy of `request.content` and call `contentHandler` once. The documentation gives no more than 30 seconds; when time runs out the system calls `serviceExtensionTimeWillExpire()` on a separate thread, where I deliver the text-only best attempt, and if neither path calls the handler the original content is shown. I can't remove the alert text, and images are limited to 10 MB.

code

swift · 37 lines
swift
import UserNotifications

final class NotificationService: UNNotificationServiceExtension {
    private let lock = NSLock()
    private var contentHandler: ((UNNotificationContent) -> Void)?
    private var bestAttempt: UNNotificationContent?

    override func didReceive(_ request: UNNotificationRequest,
                             withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttempt = request.content  // the text-only fallback
        guard let link = request.content.userInfo["seatMapURL"] as? String,
              let url = URL(string: link) else { return finish(with: request.content) }

        URLSession.shared.downloadTask(with: url) { location, _, _ in
            // Move the download out at once, to a name whose extension tells the type.
            let file = FileManager.default.temporaryDirectory
                .appendingPathComponent(UUID().uuidString + ".png")
            guard let location, (try? FileManager.default.moveItem(at: location, to: file)) != nil,
                  let map = try? UNNotificationAttachment(identifier: "seat-map", url: file),
                  let content = request.content.mutableCopy() as? UNMutableNotificationContent
            else { return self.finish(with: request.content) }
            content.attachments = [map]
            self.finish(with: content)
        }.resume()
    }

    // Called on another thread when the time is nearly up.
    override func serviceExtensionTimeWillExpire() {
        if let fallback = bestAttempt { finish(with: fallback) }
    }

    private func finish(with content: UNNotificationContent) {
        lock.lock(); let handler = contentHandler; contentHandler = nil; lock.unlock()
        handler?(content)  // only the first caller delivers
    }
}

go deeper

for a junior

Recall that a service extension is a separate target that edits an alert push before it shows, triggered by mutable-content: 1.

for a middle

Explain the two methods, the file-URL rule for attachments and why custom keys sit beside aps.

for a senior

Show the race between download and expiry, deliver exactly once, and choose a fallback that keeps the alert text within the 30-second limit.

for a principal

Decide which pushes deserve rich media at all, weighing the time limit, venue networks and the cost of a second target to maintain.

## Why a service extension exists A remote notification's payload is limited to 4 KB, so it can carry text and a few keys but never an image. A **notification service app extension** fills that gap: it is a small, separate bundle inside the app that the system runs on the device after a push arrives and **before** it is shown. Apple lists three uses: decrypting content sent encrypted, downloading media too large for the payload, and updating content with data from the device. For the concert app, the push says the gate moved and carries a link to a seat map; the extension turns that link into an image on the notification. You add it in Xcode with File > New > Target > Notification Service Extension. The template creates a subclass of `UNNotificationServiceExtension` and an `Info.plist` whose `NSExtensionPointIdentifier` is `com.apple.usernotifications.service`. ## When the system runs it The extension runs only when all of these hold: - The `aps` dictionary has `mutable-content` set to `1`. - The payload has an `alert` with a title, subtitle or body. - Alerts are allowed for the app. It never runs for silent background pushes or for pushes that only play a sound or set a badge, so the set-times refresh push in the same app never touches it. ## The two methods | Method | Role | Must do | |---|---|---| | `didReceive(_:withContentHandler:)` | Main work: change the content | Call `contentHandler` with new or original content | | `serviceExtensionTimeWillExpire()` | Last chance before the system ends the extension | Call the same handler at once with whatever is ready | Apple's documentation gives `didReceive` no more than 30 seconds. If it has not called the handler by then, the system calls `serviceExtensionTimeWillExpire()` **on a separate thread**. If neither method calls the handler, the person sees the push's **original content**, not nothing. ## Building the attachment 1. Copy the content: `request.content.mutableCopy()` gives a `UNMutableNotificationContent`. 2. Read the image URL from a custom key placed beside `aps`; custom keys appear in `userInfo`. 3. Download it, then move the downloaded file to a location you control with an extension such as `.png`, because without a type hint the attachment's type is guessed from the file extension. 4. Create `UNNotificationAttachment(identifier:url:options:)`. The URL **must be a file URL** to data on disk; passing the remote `https` URL fails. 5. Set `attachments` and call `contentHandler`. The system validates attachments after the extension finishes and moves the files into its own attachment store. Images may be JPEG, GIF or PNG up to 10 MB; audio is limited to 5 MB and movies to 50 MB. ## Racing the clock Two code paths can now finish: the download's completion and the expiry callback on another thread. The extension should deliver **exactly once**: - Keep the handler and a best-attempt content in properties when `didReceive` starts. - Guard the handler with a lock or a serial queue, and clear it after the first call, so the slower path does nothing. - Make the fallback useful. Apple's own suggestion is to deliver the text, possibly noting that an image is still downloading, rather than an empty update. ## Designing the payload for the extension The server and the extension share a small contract, and most failures come from one side changing it alone: - **Alert text that stands alone.** The original alert is the fallback whenever the download is slow, so "Your entrance moved to Gate C" must make sense without the map. - **The image link beside `aps`.** Custom keys go next to the `aps` dictionary and arrive in `userInfo`; APNs ignores custom keys placed inside `aps`. - **A category when actions matter.** The `category` key still selects the registered actions, and Apple notes that the system also uses categories when deciding whether to launch a service or content extension. - **No secrets in clear text.** Apple's guidance is to encrypt sensitive data in the payload and decrypt it in the service extension, the same hook this image download uses. ## What it cannot do - **Remove the alert.** You may change the alert text but not delete it; content without alert text makes the system ignore your changes and show the original. - **Show its own interface.** A service extension has no UI; a custom expanded look is a notification content extension, a different target. - **Change silent pushes.** Background notifications never reach it. - **Run forever.** The 30-second ceiling covers download time on a slow venue network too, so keep the image small and the fallback ready.

  • Why does the service extension never run for the set-times silent push?
    Service extensions only handle remote notifications that display an alert and carry `mutable-content: 1`. A background notification has no alert, so the system never routes it to the extension; Apple's documentation states that silent notifications, and ones that only play a sound or set a badge, cannot be modified.
  • Why must the content handler be guarded so it runs only once?
    The download's completion and `serviceExtensionTimeWillExpire()`, which the system calls on a separate thread, can both try to finish. Keeping the handler in a property, taking it under a lock and setting it to nil makes the first caller deliver and the second do nothing, so the person gets one predictable result.
  • What should the fallback content contain when the image is not ready?
    The alert text the push already carried, possibly adjusted to say the map is still loading, as Apple's documentation suggests. It must keep some alert text, because content with no alert text makes the system ignore the changes and show the original push.

  • The service extension runs for every push, including silent content-available ones.
  • UNNotificationAttachment accepts the image's remote https URL directly.
  • If time runs out, the system drops the notification entirely.
  • The extension can blank the alert text and show only the image.
  • serviceExtensionTimeWillExpire() grants another full 30 seconds to finish.