iOS — Rich pushes and extensions
Add a Notification Service Extension so iOS can show image-based and carousel pushes.
iOS handles rich-content notifications through a separate target called a Notification Service Extension (NSE). The extension runs in its own process, intercepts every incoming push before the OS displays it, and gets up to 30 seconds to download attachments and modify the content.
Without an NSE, iOS shows the title and body only — image attachments and carousel items will not render. This guide walks you through adding the NSE to your app and wiring it to the Swan SDK's Templates.renderContent(...) API.
What setup is required per notification type
| Notification type | iOS setup |
|---|---|
| Standard (title + body) | None — works out of the box |
| Image (rich media) | NSE required |
| Carousel (swipeable cards) | NSE required. The Swan SDK packs every carousel item as an UNNotificationAttachment so the NSE alone is sufficient for the default UI. If you want a custom swipeable interface, add a Notification Content Extension (NCE) — Templates.parseCarousel(_:) exposes the typed payload for you to render. |
| Custom sound | Add the sound file (.wav) to your Xcode app bundle. No extension needed — see Push notifications → Notification channels for the sound configuration. |
The most common iOS push integration issue: image / carousel notifications arriving with no image. Cause: the NSE is missing. Add it and the images render automatically.
React Native quick-setup
If your host app uses @loyalytics/swan-react-native-sdk, the SDK ships a
script that copies a ready-made NSE + NCE implementation into your ios/
directory:
node node_modules/@loyalytics/swan-react-native-sdk/scripts/setup-ios-extension.jsThe script copies:
ios/SwanNotificationServiceExtension/— handles delivery ACKs and image attachment downloads.ios/SwanNotificationContentExtension/— renders the carousel UI on long press (only needed if you use carousel pushes).
After running it, you still need to add the extension targets in Xcode, enable App Groups on all targets, and set Swift Language Version on each extension — those Xcode-side steps are detailed below.
Upgrading the React Native SDK
The extension files are copied into your ios/ folder, so upgrading the npm
package does not update them. Updating them is optional: your current
extensions keep working, and deliveries and carousel card taps are still
reported as before. Updating (in particular when moving to 2.10.0 or later)
adds right-to-left carousel layout.
To update, refresh them from your project root and rebuild the app:
node node_modules/@loyalytics/swan-react-native-sdk/scripts/setup-ios-extension.js --update--update replaces only the extensions' Swift files and keeps your
Info.plist, entitlements (App Group) and storyboard. Until you run it,
right-to-left carousels keep the left-to-right layout. The app logs [SwanSDK] ⚠️ STALE iOS EXTENSION with this command when an out-of-date extension handles a push or a
carousel tap. Package managers usually hide (npm, yarn) or skip (pnpm) a
dependency's install-time output, so do not rely on npm install to tell you:
after each upgrade run
node node_modules/@loyalytics/swan-react-native-sdk/scripts/setup-ios-extension.js --checkIt exits non-zero while an extension is out of date — add it to CI or an Xcode build phase.
Native iOS host apps (Swift / Obj-C) follow the manual setup that starts in §1 below.
1. Add the extension target in Xcode
- Open your app's
.xcworkspacein Xcode. - File → New → Target.
- Choose Notification Service Extension.
- Product name:
SwanNotificationServiceExtension(or any name you prefer). - Language: Swift.
- Click Finish. When prompted "Activate scheme?", click Cancel.
Verify in General for the new target that the Bundle Identifier is a child of your main app's bundle ID (e.g. com.yourcompany.app.SwanNotificationServiceExtension).
The extension's deployment target must be iOS 13.0+ (same as the SDK).
2. Enable App Groups on both targets
Cross-process credential sharing — required for the extension to fire killed-state delivery ACKs — runs over an App Group.
For each target (host app + NSE):
- Select the target in Xcode.
- Signing & Capabilities → + Capability → App Groups.
- Click + and enter the same identifier on both targets, e.g.
group.com.yourcompany.app.
The two targets must list the exact same App Group identifier. If they differ, the NSE can't read the host app's credentials and delivery ACKs from killed state will be silently skipped.
Then pass the identifier into your SwanConfig:
Swan.shared.initialize(
appId: "your-app-id",
config: SwanConfig(appGroup: "group.com.yourcompany.app")
)The SDK will migrate any existing credentials from the per-process store into the App Group store on first init, so apps that upgrade from an older version don't need to re-register.
3. Add the SDK to the extension target
The extension is a separate target, so it needs its own copy of SwanSDK linked in.
In your Podfile, add a target block for the extension and depend on SwanSDK:
target 'YourApp' do
pod 'SwanSDK', '~> 1.3'
# ... your other pods ...
end
target 'SwanNotificationServiceExtension' do
pod 'SwanSDK', '~> 1.3'
endRun pod install, then open the .xcworkspace again.
In Xcode, select the SwanNotificationServiceExtension target, go to General → Frameworks and Libraries, click +, and add the SwanSDK library that's already in the project from your app target's SPM dependency.
4. Replace the auto-generated NotificationService.swift
Xcode generates a placeholder NotificationService.swift when you add the extension target. Replace its body with:
import UserNotifications
import SwanSDK
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 else {
contentHandler(request.content)
return
}
// One call does both: fires the killed-state delivery ACK over
// the App Group, then renders any rich content (image,
// carousel) into the notification.
Templates.handleServiceRequest(
request: request,
content: bestAttemptContent,
appGroup: "group.com.yourcompany.app" // same as SwanConfig.appGroup
) { rendered in
contentHandler(rendered ?? bestAttemptContent)
}
}
override func serviceExtensionTimeWillExpire() {
if let contentHandler = contentHandler,
let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}That's the entire extension. Templates.handleServiceRequest(...) handles:
- Reporting the delivery, so campaign analytics counts it even when the host app is in the background or killed:
- A push sent by the Swan platform carries its own receipt token. The extension posts a
deliveredreceipt for it without needing the customer to be signed in. The receipt is saved in the App Group first and retried by the host app if the device was offline. - Other pushes post the
deliveredACK using the host-app credentials in the shared App Group suite. - The same push is counted once, even when the host app also handles it in the foreground.
- A push sent by the Swan platform carries its own receipt token. The extension posts a
- Detecting which template the payload represents (basic / carousel-manual / carousel-auto)
- Downloading the image attachments over HTTPS
- Attaching them to
UNMutableNotificationContent.attachments - Returning the modified content within the 30-second extension window
If the payload isn't a Swan-templated push, the call completes with nil and the host falls back to bestAttemptContent — the unmodified original. If the App Group isn't configured, the extension reports no delivery at all (neither the receipt nor the ACK) — rendering still runs. Configure the App Group on both targets for delivery reporting.
5. Send a test push and verify
iOS push notifications do not work on the Simulator. Test on a real device:
- Build and run on a device.
- Send a test push with an image from your Swan campaigns dashboard.
- Tap and hold (or pull down) on the notification to expand it — the image should be visible.
If the image doesn't appear, see Troubleshooting below.
6. (Optional) Custom Notification Content Extension for carousel
The default NSE-driven carousel shows the push's title and body with the image of the first card that has one — a single image, in both manual and auto mode. If your design calls for a swipeable interface (every card, page dots, per-card tap routing), add a Notification Content Extension (NCE) and render the carousel yourself.
The Swan SDK exposes the typed carousel payload via Templates.parseCarousel(_:):
extension Templates {
public static func parseCarousel(_ data: [String: String]) -> CarouselPayloadPublic?
}CarouselPayloadPublic provides items[] (each with imageURL, title, body, route, position — the card's 0-based position in the push's carouselItems — and cardIndex, the card's 1-based index on Swan platform carousels, nil otherwise), mode (.manual / .auto), variant (.standard / .filmstrip), intervalMs, defaultRoute, and route(forItemAt:) (the card's route, or defaultRoute when the card has none) — everything you need to drive your own UIKit / SwiftUI carousel view inside the NCE. The card format is in the carousel payload reference.
Open the tapped card and report which card it was
When the user taps a card, write the tap into your App Group under the key swanTemplateClickData, then hand the tap to your app with performNotificationDefaultAction(). Your app's UNUserNotificationCenterDelegate then calls Swan.shared.handleNotificationUserInfo(_:) as usual (see Getting started → iOS), and the SDK:
- opens the tapped card's
routeinstead of the push'sdefaultRoute, and - sends the click receipt with
itemIndexset to the tapped card's position (and, for a Swan platform push, the tapped receipt withcard_indexset to the card'scardIndex), so campaign analytics show which card was tapped.
// In your NotificationViewController, when the user taps card `index` of `payload`.
func openCard(at index: Int, payload: Templates.CarouselPayloadPublic, userInfo: [AnyHashable: Any]) {
guard payload.items.indices.contains(index) else { return }
var clickData: [String: Any] = [
"messageId": (userInfo["messageId"] as? String) ?? (userInfo["gcm.message_id"] as? String) ?? "",
"route": payload.route(forItemAt: index),
// The card's position in the push's carouselItems, not its index in `items`.
"itemIndex": payload.items[index].position,
"timestamp": Date().timeIntervalSince1970,
]
// Swan platform carousels number their cards from 1; legacy pushes have no cardIndex.
if let cardIndex = payload.items[index].cardIndex {
clickData["cardIndex"] = cardIndex
}
if let defaults = UserDefaults(suiteName: "group.com.yourcompany.app"), // same as SwanConfig.appGroup
let json = try? JSONSerialization.data(withJSONObject: clickData) {
defaults.set(String(data: json, encoding: .utf8), forKey: "swanTemplateClickData")
}
extensionContext?.performNotificationDefaultAction()
}| Key | Type | Value |
|---|---|---|
messageId | string | The push's messageId, or its gcm.message_id when there is no messageId. The SDK applies the click only to the tap on that notification. Leave it empty and the click can be applied to any notification's tap, and it never names a card. |
route | string | Route to open — the card's route, or defaultRoute when the card has none. |
itemIndex | integer | The tapped card's 0-based position in carouselItems (0 is the first card). Use position, which stays correct when cards without an image are left out of items. Optional: without it the card still opens, and the click receipt doesn't say which card was tapped. The receipt carries itemIndex only when messageId is set and belongs to the tapped notification. |
cardIndex | integer | The tapped card's 1-based cardIndex from carouselItems (payload.items[i].cardIndex). Swan platform carousels carry it on every card; leave it out when the card has none. The SDK sends it as the tapped receipt's card_index. It counts only together with itemIndex: click data without itemIndex names no card. |
timestamp | number | Seconds since 1970. A click older than 60 seconds is ignored. |
Your App Group must be set as SwanConfig.appGroup in the app (see step 2) and enabled on the Content Extension target too. A tap on the notification itself — not on a card — needs no click data: the push opens its defaultRoute and the click receipt has no itemIndex or card_index.
The category to register the NCE against is swan_carousel — Swan sends it as aps.category on carousel pushes whose template sets no category of its own, and the SDK stamps it on carousel content that arrives without a category. The full list of keys Swan sends to iOS is in the iOS push payload reference.
Right-to-left content. Templates.layoutDirection(_:) returns .rightToLeft when the push's content is right-to-left (for example Arabic). Set semanticContentAttribute = .forceRightToLeft on your carousel view (and its collection view) in that case so the cards, swipe direction and chevrons mirror. Card order is unchanged. A mirrored collection view puts card 1 at the right end but still opens at the left end, on the last card: once the collection view has its width (for example in layoutSubviews), scroll to the first card without animation, so the carousel opens on card 1 and a tap reports the card the user sees.
Card taps. When you persist a card tap for the host app, also write cardIndex into swanTemplateClickData: the tapped card's 1-based cardIndex from carouselItems (Swan platform carousels carry it on each card). The SDK sends it as the tapped receipt's card_index so campaign analytics can attribute the tap to the card. Leave it out for a tap that chose no card.
Troubleshooting
Delivery ACKs aren't firing in killed-app state
Symptom: campaign analytics show clicks but no deliveries when the host app is killed.
Possible causes:
- App Group identifier mismatch. Confirm the same identifier is listed under Signing & Capabilities → App Groups on BOTH the host app target AND the NSE target. They must match exactly.
- Identifier not passed to
SwanConfig. The host SDK only writes credentials into the App Group suite whenSwanConfig.appGroupis set. Pass the same string you used in the entitlement. appGroup:argument missing in the NSE. The composite call needs the App Group passed in explicitly — there's no way for the extension to discover it from the host process at runtime.- A push before the app's first start (older pushes only). For pushes without a Swan receipt token, the extension can report the delivery only after the app has started once and registered the device. On a brand-new install that receives a push before the app is first opened, that delivery is not reported. Pushes that carry a Swan receipt token are not affected.
NSE doesn't fire
Symptom: a test push arrives, but no image is attached and the NSE breakpoint never hits.
Possible causes:
- APNs payload doesn't request mutable content. Swan-issued pushes set
mutable-content: 1automatically. If you're testing with a hand-crafted payload, include that flag. - Extension target isn't in the build. Product → Scheme → Edit Scheme → Build → confirm the NSE target is listed.
- Testing on Simulator. Push notifications don't work on the iOS Simulator. Use a real device.
Image doesn't render
Possible causes:
- Image URL is not HTTPS. iOS rejects
http://attachments. - Image format isn't supported. JPEG, PNG, and GIF only. Max 10 MB.
- Network failure within the 30-second window. Check the device console for
[SwanSDK]log lines from the extension.
Build error: No such module 'SwanSDK'
The extension target doesn't have the SDK linked. Repeat Step 2 for the extension target.
Build error: Use of undeclared type 'UNNotificationServiceExtension'
The extension target's deployment target is below iOS 10. Set it to iOS 13.0+ to match the main app and the SDK.