Swan SDK
Guides

Push notifications

Receive, render, and respond to push notifications — campaigns, channels, deep linking and click acknowledgement.

Push notifications are the most common reason teams adopt Swan. This guide walks through the full lifecycle on every platform:

  1. Provider setup — register the device's push token with Swan
  2. Notification channels — register the default channels and (optionally) custom-sound channels
  3. Permission — request notification permission at the right moment
  4. Receive a campaign — what the SDK does automatically when a campaign arrives
  5. Deep linking — route taps into your app's navigation
  6. Click acknowledgement — already automatic, but how to verify

The push architecture concept explains why the SDK is wired this way. This guide is the how. The push payload reference at the end lists every key Swan sends on each platform.


1. Provider setup

The SDK ships a SwanMessagingService that subclasses FirebaseMessagingService and is declared in the SDK's own AndroidManifest.xml. You don't need to add anything to your manifest.

What you do need:

  1. Add google-services.json from your Firebase console to app/
  2. Apply the Google Services plugin in your app-level build.gradle.kts:
plugins {
    id("com.android.application")
    id("kotlin-android")
    id("com.google.gms.google-services")  // ← this
}
  1. Initialize the SDK in Application.onCreate() (covered in Getting started)

That's it. Token registration, refresh, and message delivery all run inside the SDK.

Image and carousel notifications also require a Notification Service Extension — see iOS — Rich pushes and extensions. The wire-up below covers the plain-push path; without the NSE, iOS strips rich media and displays title + body only.

Swan delivers iOS pushes through Firebase Cloud Messaging (FCM), using the Firebase credential configured for your app in Swan. FCM only accepts a Firebase registration token as the device address, so that is the token your app registers with Swan — not the raw APNs device token.

Do not pass the APNs device token from application(_:didRegisterForRemoteNotificationsWithDeviceToken:) to Swan.shared.registerAPNsToken(_:) when your Swan push credential is a Firebase credential. FCM rejects a raw APNs token, so every send to that device fails and the campaign's delivery report shows FCM_TOKEN_INVALID. Register the Firebase registration token with Swan.shared.registerAPNsTokenHex(_:) as shown below. The method name says "APNs", but it accepts any token string and registers it unchanged.

Before the code:

  1. In the Firebase console, add your iOS app to the Firebase project whose credential is configured in Swan, and upload your APNs authentication key under Project settings → Cloud Messaging.
  2. Add GoogleService-Info.plist to your app target, and add the FirebaseMessaging package (Swift Package Manager) or pod.
  3. Enable the Push Notifications capability on your app target.

Then, in your AppDelegate:

import FirebaseCore
import FirebaseMessaging
import SwanSDK
import UIKit
import UserNotifications

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()

        // Initialize Swan BEFORE Firebase can deliver a token:
        // a token passed before initialize(...) is ignored.
        Swan.shared.initialize(appId: "your-app-id")

        // On a fresh install the Firebase token can arrive before Swan has
        // finished registering the device. Register it again once Swan's
        // initialization completes (a token Swan already holds is not re-sent).
        Swan.shared.addInitializedListener {
            if let token = Messaging.messaging().fcmToken {
                Swan.shared.registerAPNsTokenHex(token)
            }
        }

        Messaging.messaging().delegate = self
        UNUserNotificationCenter.current().delegate = self
        application.registerForRemoteNotifications()
        return true
    }
}

extension AppDelegate: MessagingDelegate {
    // Fires at launch and whenever Firebase rotates the token.
    func messaging(_ messaging: Messaging,
                   didReceiveRegistrationToken fcmToken: String?) {
        guard let fcmToken, !fcmToken.isEmpty else { return }
        Swan.shared.registerAPNsTokenHex(fcmToken)
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate {
    // Forwards notification taps to the SDK (deep links + click tracking).
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        Swan.shared.handleNotificationUserInfo(response.notification.request.content.userInfo)
        completionHandler()
    }
}

Firebase Messaging hands the APNs device token to Firebase for you. Only if you have turned off Firebase's app-delegate proxy (FirebaseAppDelegateProxyEnabled set to NO in Info.plist), forward it to Firebase yourself. Otherwise Firebase cannot link the device to APNs, so pushes to the device are not delivered, even if a Firebase registration token is registered with Swan. This is not a Swan registration — Swan still gets the Firebase token from the delegate above:

// Only when FirebaseAppDelegateProxyEnabled = NO.
func application(_ application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken  // to Firebase, not to Swan
}

Check the registration. After launch, Swan.shared.getPushToken() returns the token Swan holds for this device and Swan.shared.isPushReady() returns true once it is registered:

print(Swan.shared.getPushToken() ?? "none", Swan.shared.isPushReady())

A Firebase registration token looks like <instance-id>:APA91b… (a long string containing a colon). If you see a 64-character hex string instead, the app registered the raw APNs token — switch to the Firebase token as above.

For the exact payload Swan sends to iOS, see the iOS push payload reference.

The SDK delivers pushes through React Native Firebase + Notifee. Register all handlers at module scope in index.js (not inside a component) so background and killed-state deliveries fire before the React tree mounts.

// index.js
import messaging from '@react-native-firebase/messaging';
import notifee from '@notifee/react-native';
import {
    createForegroundMessageHandler,
    createBackgroundMessageHandler,
    createNotificationOpenedHandler,
    createNotifeeForegroundHandler,
    createNotifeeBackgroundHandler,
} from '@loyalytics/swan-react-native-sdk';

messaging().onMessage(createForegroundMessageHandler());
messaging().setBackgroundMessageHandler(createBackgroundMessageHandler());

notifee.onForegroundEvent(createNotifeeForegroundHandler());
notifee.onBackgroundEvent(createNotifeeBackgroundHandler());

// iOS carousel taps surface through this Firebase handler — Notifee click
// handlers do not fire for carousel deliveries displayed natively by iOS.
messaging().onNotificationOpenedApp(createNotificationOpenedHandler());

Then enable push during SDK init:

import SwanSDK from '@loyalytics/swan-react-native-sdk';

const sdk = SwanSDK.getInstance('your-app-id', {
    isProduction: true,
    pushNotifications: { enabled: true },
});

On iOS, image and carousel pushes additionally require a Notification Service Extension (and, for carousel, a Notification Content Extension) — see iOS — Rich pushes and extensions.

Web push uses the Web Push (VAPID) standard. The SDK ships a Service Worker; serve dist/sw.js from @loyalytics/swan-web-sdk at /swan-service-worker.js on your origin (see the getting-started guide for build-tool recipes). The SDK reads your per-tenant VAPID public key from the device-register response automatically — no key copy/paste needed:

import { Swan } from '@loyalytics/swan-web-sdk';

Swan.initialize('your-app-id', { production: true });

if (await Swan.isPushSubscribed()) {
  // Already opted in — nothing to do.
} else {
  // Show your "Enable notifications" CTA. Call subscribeToPush() on click.
  const subscribed = await Swan.subscribeToPush();
  // → true on success; false if permission denied or browser unsupported.
}

Swan.addNotificationOpenedListener(({ route, keyValuePairs }) => {
  if (route) router.push(route);
});

Coverage: Chrome / Edge / Firefox (desktop + Android) — full · Safari macOS 13+ — full · iOS Safari 16.4+ — only when installed as a PWA · iOS Safari < 16.4 — not supported (SDK returns false from subscribeToPush gracefully).


2. Notification channels

The SDK pre-registers five default channels on first init:

Channel IDImportance
swan_transactionalHigh
swan_alertsHigh
swan_promotionalDefault
swan_generalDefault
swan_notificationsDefault

The campaign payload chooses the channel by ID — you don't have to do anything unless you want a custom-sound channel (the OS binds the sound to the channel at creation, so you can't change a sound on an existing channel):

import cx.swan.sdk.Swan
import cx.swan.sdk.SWAN_NOTIFICATION_CHANNELS

Swan.createNotificationChannel(
    channelId = "order_updates",
    channelName = "Order updates",
    importance = SWAN_NOTIFICATION_CHANNELS.IMPORTANCE_HIGH,
    soundResName = "order_chime",  // res/raw/order_chime.mp3
)

Call this once at app launch (it's idempotent — calling it again on the same channelId is a no-op).

iOS doesn't have OS-level channels; UNNotificationCategory serves a similar role. The SDK pre-registers the five default categories at init (their ids are exposed as SwanNotificationChannels.transactional, .alerts, .promotional, .general, .default) — these are the same string values as the Android channel ids, so campaign payloads work cross-platform without a remap.

Custom UNNotificationCategory registration (action buttons, custom intents) is a host-app concern — register your categories via UNUserNotificationCenter.current().setNotificationCategories(_:) directly, and have the campaign payload reference your category id.

The SDK pre-registers five default channels on first init. On Android these are OS-level notification channels; on iOS the equivalent UNNotificationCategory entries are registered under the same string IDs so campaign payloads work cross-platform without a remap.

ConstantChannel IDImportance (Android)
SWAN_NOTIFICATION_CHANNELS.TRANSACTIONALswan_transactionalHigh
SWAN_NOTIFICATION_CHANNELS.ALERTSswan_alertsHigh
SWAN_NOTIFICATION_CHANNELS.PROMOTIONALswan_promotionalDefault
SWAN_NOTIFICATION_CHANNELS.GENERALswan_generalDefault
SWAN_NOTIFICATION_CHANNELS.DEFAULTswan_notificationsDefault

The campaign payload chooses the channel by ID — you don't have to do anything unless you want a custom-sound channel (the OS binds the sound to the channel at creation, so you can't change a sound on an existing channel).

import SwanSDK, {
    SWAN_NOTIFICATION_CHANNELS,
} from '@loyalytics/swan-react-native-sdk';

const sdk = SwanSDK.getCurrentInstance();

console.log(SWAN_NOTIFICATION_CHANNELS.TRANSACTIONAL); // 'swan_transactional'

// Custom channel (Android only — no-op on iOS):
await sdk?.createNotificationChannel(
    'Order updates',     // channelName
    4,                   // importance (4 = High)
    'Shipping + delivery',
    'order_updates',     // channelId
    'order_chime'        // sound file in res/raw/
);

Web Notifications API has no channel concept; styling is controlled at the campaign level.


3. Request notification permission

On Android 13+ (API 33) notification permission is runtime, like camera or location. Earlier versions auto-grant.

class MyActivity : AppCompatActivity() {
    override fun onResume() {
        super.onResume()
        Swan.setCurrentActivity(this)   // required for the permission dialog
    }

    override fun onPause() {
        Swan.setCurrentActivity(null)
        super.onPause()
    }

    private fun askForPushPermission() {
        lifecycleScope.launch {
            val granted = Swan.requestNotificationPermission()
            if (granted) {
                // happy path
            } else {
                // user denied — show a soft prompt explaining what they'll miss
            }
        }
    }
}

requestNotificationPermission is a suspend function that returns Boolean. The OS dialog needs an Activity context — register the current Activity via Swan.setCurrentActivity(this) in onResume. If you forget, the call still resolves (returning false) but no dialog will appear.

Best practice: don't ask at first launch — ask after the user has done one meaningful action (signed in, added to cart, completed onboarding). Permission denials are sticky on Android.

let granted = await Swan.shared.requestNotificationPermission()

Same principle: ask after a meaningful action, not at cold launch. iOS denials are also sticky and the user has to go to Settings to flip them back.

const sdk = SwanSDK.getCurrentInstance();
const granted = await sdk?.requestNotificationPermission();

Handles the platform differences (Android 13+ runtime prompt, iOS prompt, older Android auto-grant) internally.

const granted = await Swan.requestPushPermission();

Browser permission UI varies — Chrome / Edge show inline prompts; Safari uses its own model. The SDK exposes the boolean outcome consistently.


4. Receive a campaign

When the Swan backend sends a campaign to a registered device, the SDK:

  1. Receives the data-only payload via the platform's messaging service
  2. Parses the template (basic, carousel-manual, carousel-auto) from the payload
  3. Posts the notification through the OS notification API on the correct channel (Android) / category (iOS)
  4. Awaits user interaction

You do not write a "render notification" callback. That's the SDK's job. What you do wire up is the listener for the user's tap (next section).

If you need to observe incoming pushes (for analytics, debugging, or to add your own in-app UI), subscribe a listener:

Swan.addPushNotificationReceivedListener { payload ->
    Log.d("MyApp", "push received: ${payload.messageId}")
}

Payload structure — PushNotificationReceivedPayload:

FieldTypeDescription
messageIdString?The Swan message id (data.messageId) when the push carries one (Swan platform pushes with delivery receipts do), otherwise FCM RemoteMessage.getMessageId(). null when neither is present.
titleString?Title from the FCM data["title"] field. null if the payload omits it.
bodyString?Body from the FCM data["body"] field. null if the payload omits it.
dataMap<String, String>The raw FCM data map as delivered. String-only per FCM wire enforcement — the SDK does not pre-parse known keys.

The event fires when a push that shows a notification arrives while the SDK is running in your app's process (app in the foreground, or in the background with Swan.init already called), BEFORE the SDK posts the system notification, and when a silent push (data["silent"] == "true") arrives, which posts no notification. It does not fire for a push with no title, body or route (nothing is shown and nothing is reported to your app), and it does not fire when the push wakes your app before Swan.init runs. Receiving a push never fires addNotificationOpenedListener; that listener fires only when the user taps the notification. The event is not buffered — late subscribers do not see prior pushes.

Swan.shared.addPushNotificationReceivedListener { payload in
    print("push received:", payload.messageId ?? "(no id)")
}

Payload structure — PushNotificationReceivedPayload:

FieldTypeDescription
messageIdString?The Swan message id (top-level messageId) when the push carries one (Swan platform pushes with delivery receipts do), otherwise the Firebase gcm.message_id. APNs itself delivers no message id; the SDK also reads an id key inside aps if your own pushes set one. nil when none of these is present.
titleString?Title from the push's aps.alert. nil if the payload omits it.
bodyString?Body from the push's aps.alert. nil if the payload omits it.
data[String: String]The raw push data map as delivered. APNs userInfo is flattened to a string map so the shape matches Android: every top-level string or number value except aps (nested objects such as fcm_options are skipped). The SDK does not pre-parse known keys.

Fires only for foreground deliveries, BEFORE the SDK posts the system notification. Background / killed-state pushes route through addNotificationOpenedListener. Not buffered — late subscribers do not see prior pushes.

Every key Swan puts in an iOS push is listed in the iOS push payload reference.

import SwanSDK from '@loyalytics/swan-react-native-sdk';

const sdk = SwanSDK.getCurrentInstance();

sdk?.addEventListener(SwanSDK.EVENTS.PUSH_NOTIFICATION_RECEIVED, (notification) => {
    console.log('push received:', notification);
});

Payload structure — the raw FCM RemoteMessage delivered to the foreground handler. The most common fields:

FieldTypeDescription
messageIdstring | undefinedFCM transport-layer message id.
dataRecord<string, string> | undefinedThe FCM data map as delivered. Includes title, body, route, keyValuePairs (JSON-encoded), and any campaign-specific fields.
notificationobject | undefinedPresent only when the campaign was sent as a notification message rather than data-only; the SDK uses data-only for full control over presentation.

PUSH_NOTIFICATION_RECEIVED fires only for foreground data-only messages received via messaging().onMessage. Background and killed-state deliveries route through the tap path (NOTIFICATION_OPENED).

The Web SDK has no push-received listener. Pushes arrive in the Swan service worker, outside your page: the service worker shows the notification and sends the delivery receipt itself. Your page hears about a push when the user clicks the notification, through addNotificationOpenedListener (see Deep linking on tap).

What the service worker receives is listed in the Web push payload reference.


5. Deep linking on tap

The campaign payload can carry a deep-link route (route / defaultRoute — see the push payload reference). On Android, iOS and React Native, a tap opens your app (cold-start or warm). On the web, the Swan service worker handles the click and passes it to open tabs of your site — see How the Swan service worker handles it. The SDK then delivers the tap to these listeners:

  • addNotificationOpenedListener — gets the full payload, fires for every notification tap regardless of whether there's a deep link
  • addDeepLinkOpenedListener — fires only when the push has a deep-link route; a tap on a push without one fires only addNotificationOpenedListener
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Required on cold-start to capture the launching intent
        Swan.handleNotificationIntent(intent)

        Swan.addDeepLinkOpenedListener { payload ->
            payload.route?.let { navController.navigate(it) }
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        // Required on warm-start (notification tap while app is backgrounded)
        Swan.handleNotificationIntent(intent)
    }
}

Cold-start gotcha: the SDK deduplicates by messageId for 30 seconds. Calling handleNotificationIntent from both onCreate and onNewIntent is safe — only one delivery fires for any given message.

Payload structure — NotificationOpenedPayload (delivered to addNotificationOpenedListener):

FieldTypeDescription
routeString?Deep-link target — either a path (/products/123) or a full URL (https://example.com/p/1, myapp://offer/abc). null when the campaign sent no route. Empty strings on the wire are normalized to null.
titleString?Notification title (FCM data.title).
bodyString?Notification body (FCM data.body).
keyValuePairsMap<String, Any?>Custom key/value pairs from the campaign, parsed from the keyValuePairs JSON-encoded wire field. Always non-null — empty map when absent, empty, or unparseable. Values are primitives, nested maps, or lists.
extrasMap<String, String>Remaining FCM data fields the SDK does not consume directly. Preserved verbatim — reach for oneLinkParams, oneLinkConfig, or any custom fields here.

DeepLinkOpenedPayload (delivered to addDeepLinkOpenedListener) has route, keyValuePairs, and extras with the same semantics, plus a source: DeepLinkOpenedPayload.Source enum (PUSH, EMAIL, SMS, DEEP_LINK) indicating where the deep link originated.

Swan.shared.addDeepLinkOpenedListener { payload in
    if let route = payload.route { router.navigate(to: route) }
}

// Forward UNUserNotificationCenter callbacks into
// Swan.shared.handleNotificationUserInfo(_:) from your
// UNUserNotificationCenterDelegate to drive cold-start + warm-start.

Payload structure — NotificationOpenedPayload (delivered to addNotificationOpenedListener):

FieldTypeDescription
routeString?Deep-link target — either a path or a full URL. nil when the campaign sent no route. Empty strings on the wire are normalized to nil.
titleString?Notification title (push data.title).
bodyString?Notification body (push data.body).
keyValuePairs[String: JSONValue]Custom key/value pairs from the campaign, parsed from the keyValuePairs JSON-encoded wire field. Always non-nil — empty dictionary when absent or unparseable. JSONValue preserves primitives and nested objects / arrays.
extras[String: String]Remaining data fields the SDK does not consume directly. Preserved verbatim — reach for oneLinkParams, oneLinkConfig, or any custom fields here. APNs userInfo is flattened to a string map for parity with FCM.

DeepLinkOpenedPayload (delivered to addDeepLinkOpenedListener) has route, keyValuePairs, and extras with the same semantics, plus a source: DeepLinkOpenedPayload.Source enum (.push, .email, .sms, .deepLink) indicating where the deep link originated.

import SwanSDK from '@loyalytics/swan-react-native-sdk';

useEffect(() => {
    const sdk = SwanSDK.getCurrentInstance();
    const handler = (payload) => {
        if (payload.route) navigation.navigate(payload.route, payload.keyValuePairs);
    };
    const sub = sdk?.addListener(SwanSDK.EVENTS.NOTIFICATION_OPENED, handler);
    return () => sub?.remove();
}, []);

NOTIFICATION_OPENED and DEEP_LINK_OPENED are emitted on the SDK instance and consumed via addListener(event, callback) (returns { remove(): void }). The separate addEventListener API is reserved for FCM-provider events such as PUSH_NOTIFICATION_RECEIVED and TOKEN_RECEIVED.

Payload structure — NotificationOpenedPayload:

FieldTypeDescription
routestring | undefinedDeep-link target — either a path or a full URL. undefined when the campaign sent no route.
messageIdstring | undefinedSwan's message id (data.messageId) — the same value whether the push arrived through FCM or was recovered. A push without one carries the FCM message id instead. The FCM message id is also passed as gcm.message_id.
titlestring | undefinedNotification title.
bodystring | undefinedNotification body.
keyValuePairsRecord<string, any>Custom key/value pairs parsed from the JSON-encoded keyValuePairs wire field. The SDK parses it for you.
[key: string]anyAdditional notification data fields are passed through on the payload (e.g. oneLinkParams, notificationType, channelId, campaign-specific keys).

DeepLinkOpenedPayload has route, keyValuePairs, and the index signature with the same semantics, plus a source: 'push' | 'email' | 'sms' | 'deepLink' indicating where the deep link originated.

Cold-start is handled automatically via the message handlers registered in index.js — see Getting started → React Native.

Swan.addDeepLinkOpenedListener((payload) => {
    if (payload.route) router.push(payload.route);
});

Web "deep links" route through the SDK's service worker on notification click — the bundled Service Worker forwards the click into the page, and your listener fires on the next message tick.

Payload structure — PushNotificationReceivedPayload (delivered to both addNotificationOpenedListener and addDeepLinkOpenedListener):

FieldTypeDescription
messageIdstring | nullSwan's ID for the message, from the push's data.commId.
titlestring | nullNotification title. null if omitted.
bodystring | nullNotification body. null if omitted.
routestring | nullDeep-link route from the push's data.route or data.defaultRoute. null when the push has neither — see the Web push payload reference. addDeepLinkOpenedListener only fires when route is non-null.
keyValuePairsReadonly<Record<string, string>> | nullKey/value pairs from the push's data.keyValuePairs, parsed into an object. null when the push has none.

6. Token + permission listeners

Subscribe to push-provider lifecycle events for analytics, debugging, or to mirror the token in your own backend.

val unsubRegistered = Swan.addPushTokenRegisteredListener { event ->
    Log.d("push", "FCM token registered with Swan: ${event.token}")
}

val unsubRefresh = Swan.addPushTokenRefreshListener { event ->
    Log.d("push", "FCM token rotated: ${event.token}")
}

val unsubFailed = Swan.addPushTokenRegistrationFailedListener { event ->
    Log.w("push", "token subscribe failed: ${event.error.message}")
}

Payload structure — TelemetryEvent.PushTokenRegistered and TelemetryEvent.PushTokenRefreshed:

FieldTypeDescription
tokenStringThe current FCM token.

addPushTokenRegisteredListener fires on every successful subscribe with the Swan backend (initial registration AND every rotation). It buffers the most recent token, so late subscribers receive the current token synchronously on subscribe.

addPushTokenRefreshListener fires only on FCM token rotation (onNewToken) — not on the initial registration. Useful if you maintain your own copy of the token in a remote backend.

Payload structure — TelemetryEvent.PushTokenRegistrationFailed:

FieldTypeDescription
errorThrowableThe underlying failure from the FCM subscribe POST (network error, 4xx, malformed response).

The SDK continues to function — events keep queuing locally and the next onNewToken or Swan.registerFcmToken(...) call retries the subscribe.

let unsubRegistered = Swan.shared.addPushTokenRegisteredListener { payload in
    print("Push token registered with Swan:", payload.token)
}

let unsubRefresh = Swan.shared.addPushTokenRefreshListener { payload in
    print("Push token rotated:", payload.token)
}

let unsubFailed = Swan.shared.addPushTokenRegistrationFailedListener { payload in
    print("token subscribe failed:", payload.error.localizedDescription)
}

let unsubPermission = Swan.shared.addPushPermissionListener { event in
    // event is `.permissionGranted` or `.permissionDenied`
}

Payload structure — PushTokenRegisteredPayload and PushTokenRefreshPayload:

FieldTypeDescription
tokenStringThe token string registered with Swan, exactly as your app passed it — the Firebase registration token when you follow Provider setup.

addPushTokenRegisteredListener fires on every successful push-token registration with the Swan backend (including the initial registration). Re-registering the same token the SDK already holds short-circuits without re-emitting.

addPushTokenRefreshListener fires only when a re-registration replaces a previous token. The initial registration does NOT fire this surface.

Payload structure — PushTokenRegistrationFailedPayload:

FieldTypeDescription
errorErrorThe underlying failure from the SDK's POST to /device/push-subscription.

The SDK continues to function — events queue locally and the next Swan.shared.registerAPNsTokenHex(_:) call retries the subscribe.

addPushPermissionListener callback receives a PushLifecycleEvent — .permissionGranted or .permissionDenied — fired on every requestNotificationPermission() resolution.

import SwanSDK from '@loyalytics/swan-react-native-sdk';

const sdk = SwanSDK.getCurrentInstance();

sdk?.addEventListener(SwanSDK.EVENTS.TOKEN_RECEIVED, (token) => {
    console.log('FCM token received:', token);
});

sdk?.addEventListener(SwanSDK.EVENTS.TOKEN_REFRESH, (newToken) => {
    console.log('FCM token rotated:', newToken);
});

sdk?.addEventListener(SwanSDK.EVENTS.PERMISSION_CHANGED, (granted) => {
    console.log('permission:', granted ? 'granted' : 'denied');
});

Callback payloads:

Event constantCallback parameter
SwanSDK.EVENTS.TOKEN_RECEIVEDtoken: string — the FCM token generated after permission is granted.
SwanSDK.EVENTS.TOKEN_REFRESHtoken: string — the new FCM token after rotation.
SwanSDK.EVENTS.PERMISSION_CHANGEDgranted: boolean — true if the user granted notification permission, false if denied.

Listeners registered before push initialization are queued and attached when push init completes.

The Web SDK does not expose a separate token-received listener — the Push API subscription is managed through subscribeToPush() / isPushSubscribed() / unsubscribePush(). Permission state changes are observable via the browser's Permissions API:

const status = await navigator.permissions.query({ name: 'notifications' });
status.onchange = () => {
    console.log('permission now:', status.state);
};

7. Turn push notifications off and on

Use unsubscribePush() when a customer turns notifications off in your app, and subscribePush() when they turn them back on. After unsubscribePush() the device stays unsubscribed — across app launches, push token refreshes, login and logout — until your app calls subscribePush(). Your existing token-forwarding and permission calls don't turn push back on, so you can keep making them at launch. On Android, iOS and React Native, if the customer toggles quickly, the last call wins, even when you don't wait for the previous call to finish (on Android, subscribePush() counts from when its coroutine runs). On Web, wait for each call to finish before making the next.

Upgrading from an earlier SDK version.

  • React Native: a device that unsubscribed on an earlier version stays unsubscribed after the app is upgraded. Nothing to do.
  • Android 1.1.4 and iOS 1.5.4 and earlier stored no opt-out, and the new versions do not guess one. A device that unsubscribed on them counts as subscribed after the upgrade, and the next token sync registers it again. If your app keeps its own push setting and it is off, call unsubscribePush() once after upgrading:
// Android — once, after upgrading (e.g. at launch, behind your own flag)
if (!myPushSettingIsOn) Swan.unsubscribePush()
// iOS
if !myPushSettingIsOn { Swan.shared.unsubscribePush() }
// Customer turns notifications off
Swan.unsubscribePush()

// Customer turns notifications back on
lifecycleScope.launch {
    Swan.subscribePush()
        .onSuccess { token ->
            // token is the registered token: push is back on.
            // null: Firebase can't provide a token yet (e.g. before
            // notification permission is granted) — push is on and the SDK
            // registers it once Firebase does — or unsubscribePush() was
            // called again before this finished, and push is off.
        }
        .onFailure { error ->
            // SDK not initialized or push disabled in SwanConfig: nothing
            // changed. Firebase / network error: push is back on but the
            // token isn't registered yet. It is registered with the next
            // token refresh or registerFcmToken / requestFcmToken call, or
            // call subscribePush() again.
        }
}

While unsubscribed, registerFcmToken does nothing and requestFcmToken() returns null.

// Customer turns notifications off
Swan.shared.unsubscribePush()

// Customer turns notifications back on
Swan.shared.subscribePush()

Keep forwarding your push token on every launch exactly as set up in Provider setup — with the Firebase setup, the Firebase registration token through registerAPNsTokenHex(_:). While unsubscribed, the SDK keeps the latest token without registering it; subscribePush() registers it. From Objective-C, call [[SwanObjC shared] subscribePush].

const sdk = SwanSDK.getCurrentInstance();

// Customer turns notifications off
await sdk?.unsubscribePush();

// Customer turns notifications back on — requests permission if needed
const granted = await sdk?.subscribePush();

subscribePush() resolves to true when notification permission is granted. The SDK also registers the push token at launch only when notification permission is granted.

await Swan.unsubscribePush();
const subscribed = await Swan.subscribeToPush();

8. Delivery and tap receipts

Receipts are automatic — you don't wire them up, and you don't call any acknowledgement method.

  • Delivered is reported as soon as the push reaches the device, in every app state (foreground, background and killed). A silent push is reported as delivered only.
  • Tapped is reported once per tap of the notification. Showing a notification is never reported as a tap, and a silent push is never reported as tapped. Tapping a card of a carousel the user swipes through reports which card was tapped (on native iOS, when your Notification Content Extension records the tapped card; see Open the tapped card and report which card it was). A tap that doesn't choose a card is reported as a tap on the push: on Android, a tap outside the cards or on an auto-advancing carousel; on iOS, a tap on the collapsed notification.
  • Receipts are saved on the device first and retried automatically if the device is offline, for up to 7 days. The same receipt is never counted twice.
  • Pushes sent by the Swan platform carry their own receipt token, so receipts are reported whether or not the customer is signed in.

What your app needs for complete receipts:

  • Android: the SDK's messaging service (the default, or a subclass of SwanMessagingService that calls super.onMessageReceived). It reports every push it receives, so you don't need ackPushDelivered; a call for a push the SDK has already reported is ignored. If your own FirebaseMessagingService shows Swan pushes instead, the SDK never sees them: they are reported as delivered only if you call ackPushDelivered, and pushes sent by the Swan platform send no receipts.
  • iOS: a Notification Service Extension calling Templates.handleServiceRequest(...) and an App Group shared with the app (see iOS — Rich pushes and extensions). Without the extension, a push that arrives while the app is in the background is not reported as delivered. In the foreground, pass the notification to handlePushNotificationUserInfo from willPresent.
  • React Native: the SDK's foreground and background message handlers (and, on iOS, its Notification Service Extension).

To confirm receipts on a device:

  • Android: grep logcat for [SwanSDK] Push receipt (pushes sent by the Swan platform) or [SwanSDK] Notification ACK queued (other pushes)
  • iOS: search the console for [SwanSDK] Notification receipt queued or [SwanSDK] Notification ACK queued
  • RN: a POST /v1/push/receipts in your network inspector (pushes sent by the Swan platform), or the [SwanSDK] Notification ACK queued log marker
  • Web: check the network tab for a /events POST with type: "push_clicked"

If you don't see this within a second of a tap, file an issue with the messageId and we'll trace it backend-side.

Right-to-left carousels

When a carousel's text is right-to-left (for example Arabic), the expanded carousel is laid out right to left: the previous and next controls and the slide direction are mirrored and the text is right-aligned. Card order does not change. On Android this needs android:supportsRtl="true" on your <application> element (the default for new projects).

Recover missed pushes (Android)

Android phones sometimes never receive a push that Swan sent: the phone was offline, or the system stopped the app in the background. With the Android SDK 1.2.0 or later, or the React Native SDK 2.10.0 or later on Android, the SDK fetches such a push later and shows it, once, while it is still valid.

Swan turns recovery on for each push integration; there is nothing to add to your app. The SDK checks for missed pushes:

  • when the app opens and every time it comes to the foreground (after Swan.init), and
  • in the background every few hours (four hours unless Swan sets another interval), only while the phone is online and the battery is not low. The background check also runs when your app's process was not started by the user, and needs no Swan.init in that process.

How recovered pushes behave:

  • A push is shown at most once, however it arrives. If the original push reaches the phone after a recovered copy was shown (or the other way round), the second one is skipped — no second notification, sound or badge, and no second delivery report.
  • A push whose offer or campaign has ended is never shown, including an original push that reaches the phone too late.
  • At most one recovered notification is shown every 5 minutes; any others wait for the next check.
  • A recovered push is shown exactly like the original: standard, image, and carousel (manual, auto and filmstrip), on the same channel and with the same sound.
  • Its tap opens your launcher activity like any Swan push, and Swan.handleNotificationIntent(intent) reports it to addNotificationOpenedListener and addDeepLinkOpenedListener as usual. While the SDK is initialized, addPushNotificationReceivedListener also fires when a recovered push is shown.
  • Recovered pushes are reported as delivered and tapped like any other push, marked as recovered in campaign reports.
  • Nothing is fetched or shown while push is off for the app — SwanConfig(pushNotifications = PushNotificationsConfig(enabled = false)), after Swan.unsubscribePush() (until Swan.subscribePush(), which turns recovery back on straight away), or when the user has turned off notifications for your app in system settings.

Which messaging service handles Swan pushes. Recovery relies on the SDK seeing every Swan push, so it can skip a copy it has already shown.

  • The SDK's built-in SwanMessagingService (the default). Nothing to do.

  • Your own subclass of SwanMessagingService. Call super so Swan pushes go through the SDK:

    class MyMessagingService : SwanMessagingService() {
        override fun onMessageReceived(message: RemoteMessage) {
            super.onMessageReceived(message) // Swan shows, de-duplicates and reports its pushes
            // ...your own handling of non-Swan messages
        }
    
        override fun onNewToken(token: String) {
            super.onNewToken(token)
            // ...
        }
    }
  • Your own FirebaseMessagingService that shows Swan pushes itself. The SDK never sees those pushes, so it can't tell that one was already shown and may show a recovered copy as well. Let the SDK show Swan pushes instead: subclass SwanMessagingService as above.

Launch intent. The tap intent of a recovered push carries one more string extra, swanPushPath = recovered, which the SDK uses for the tap report. It is reserved: the SDK leaves it out of the payloads it passes to your listeners.

Dependencies and backup. The background check uses Android WorkManager: the SDK adds androidx.work:work-runtime-ktx 2.9.1 to your app. WorkManager merges its own manifest entries into your app: the WAKE_LOCK, ACCESS_NETWORK_STATE, RECEIVE_BOOT_COMPLETED and FOREGROUND_SERVICE permissions, plus its services and receivers. The check uses the push token your app already registered with Swan; it never asks Firebase for a new one. The SDK keeps its record of shown pushes out of Android backup and device-to-device transfer; its device id is already excluded, so there is nothing to configure.

To see recovery on a device, initialize with SwanConfig(debug = true) and filter logcat by the tag Swan.PushAmp (each check and every recovered push that was skipped, with the reason) and by handleFcmInbound: push not drawn (an original push skipped because it was already shown or has expired).

Android phones sometimes never receive a push that Swan sent: the phone was offline, or the system stopped the app in the background. With the React Native SDK 2.10.0 or later on Android, the SDK fetches such a push later and shows it, once, while it is still valid.

Swan turns recovery on for each push integration; there is nothing to add to your app. The SDK checks for missed pushes:

  • every time the app opens or comes to the foreground, and
  • in the background every few hours (four hours unless Swan sets another interval), only while the phone is online and the battery is not low.

How recovered pushes behave:

  • A push is shown at most once, however it arrives. If the original push reaches the phone after a recovered copy was shown (or the other way round), the second one is skipped — no second notification, sound or badge.
  • A push whose offer or campaign has ended is never shown.
  • At most one recovered notification is shown every 5 minutes; any others wait for the next check.
  • A recovered push looks and behaves exactly like the original (standard and carousel), and its taps reach NOTIFICATION_OPENED and DEEP_LINK_OPENED as usual.
  • Recovered pushes are reported as delivered and tapped like any other push, marked as recovered in campaign reports.
  • Nothing is fetched or shown while push is off for the app — your pushNotifications.enabled setting, after unsubscribePush() (until subscribePush(), which turns recovery back on straight away), or when the user has turned off notifications for your app in system settings.

What your app needs:

  • The SDK's message handlers from Provider setup (createBackgroundMessageHandler, createForegroundMessageHandler) and @notifee/react-native, as for any Swan push.
  • The background check uses Android WorkManager. The SDK adds androidx.work:work-runtime-ktx 2.9.1 to your Android build, which needs your app's compileSdkVersion to be 34 or higher (see React Native setup).

Android backup. The SDK keeps its record of shown pushes out of Android backup and device-to-device transfer, and when it finds its saved device id restored from another installation it registers the phone as a new device. To keep the device id itself out of backups too, exclude React Native's AsyncStorage database. This also excludes everything else your app keeps in AsyncStorage, so only do it if that suits your app.

<!-- android/app/src/main/res/xml/data_extraction_rules.xml (Android 12+) -->
<data-extraction-rules>
  <cloud-backup>
    <exclude domain="database" path="RKStorage" />
  </cloud-backup>
  <device-transfer>
    <exclude domain="database" path="RKStorage" />
  </device-transfer>
</data-extraction-rules>
<!-- android/app/src/main/res/xml/backup_rules.xml (Android 11 and lower) -->
<full-backup-content>
  <exclude domain="database" path="RKStorage" />
</full-backup-content>
<!-- android/app/src/main/AndroidManifest.xml -->
<application
  android:dataExtractionRules="@xml/data_extraction_rules"
  android:fullBackupContent="@xml/backup_rules"
  ...>

To see recovery on a device, initialize the SDK with logging: true and grep logcat for [SwanSDK] recovered push (a recovered push that was skipped, with the reason) and [SwanSDK] Push not drawn (an original push skipped because it was already shown or has expired).


Push payload reference

This section lists exactly what Swan sends to a device on each platform. The SDK reads all of it for you. You need this reference only when you write your own Notification Service Extension or Content Extension, your own FirebaseMessagingService, or your own service worker, or when you check a payload while debugging.

A React Native app receives the Android payload on Android devices and the iOS payload on iOS devices.

How to read the tables:

  • Everything below describes pushes to devices registered by a current Swan SDK. Devices registered by an older SDK version can receive a different payload — see Payload for older SDK versions.
  • Always means every Swan push to that platform carries the key. Every other key is present only under the condition given.
  • On Android and iOS, every Swan key holds a string. Keys described as JSON-encoded hold a JSON document inside that string — parse it before you use it.
  • Swan doesn't send the deep-link route the same way on every push. Some pushes carry both defaultRoute and route, some carry only defaultRoute, and a push with no route may carry both as empty strings. Resolve the route the way the SDK does: route if it is a non-empty string, otherwise defaultRoute if it is a non-empty string, otherwise there is no route.

Android push payload reference

Delivery

Every Android push to a device registered by a current Swan SDK is an FCM data message (for older SDK versions, see Payload for older SDK versions): there is no notification block, only a data map, and the message is sent with Android priority high (RemoteMessage.getOriginalPriority() returns PRIORITY_HIGH). Because there is no notification block, Android passes every Swan push to the SDK's messaging service — in the foreground, in the background, and after the app was closed (but not after the user force-stops it) — and the SDK builds and posts the notification itself.

Data keys

KeyWhen presentValue
titleAlwaysNotification title from the template. Empty string when the template has no title.
bodyAlwaysNotification body from the template.
defaultRouteCampaign has a routeThe campaign's deep-link route. Some pushes also carry it as an empty string when the campaign has no route.
routeSome pushesSame value as defaultRoute. See How to read the tables for how to resolve the route.
imageTemplate has an imageImage URL.
soundTemplate sets a soundThe template's sound value as entered: default, silent, or the name of a custom sound.
channelIdTemplate sets an Android channelChannel ID, for example swan_promotional.
keyValuePairsCampaign has key/value pairs for AndroidJSON-encoded object of the pairs targeted at Android or at both platforms, for example "{\"offerId\":\"WKND40\"}". Pairs targeted only at iOS are left out. Every value is a string.
notificationTypeCarousel push"carousel". Not present on standard pushes.
carouselModeCarousel push, when setmanual or auto — see Carousel payload reference.
carouselVariantCarousel push, when setstandard or filmstrip.
carouselItemsCarousel push with cardsJSON-encoded array of cards — see Card format.
oneLinkParamsCampaign has OneLink parametersJSON-encoded object — see OneLink keys.
oneLinkConfigCampaign has a OneLink configurationJSON-encoded object — see OneLink keys.
dispatchIdPushes sent by the Swan platformIdentifies this push to this device. The SDK uses it to show a push only once (see Recover missed pushes).
expiresAtPushes to an app with missed-push recovery turned onTime after which the push is no longer shown, in Unix seconds, for example "1760086400".

Firebase keeps its own metadata — message ID, sent time, sender — on the RemoteMessage object (getMessageId(), getSentTime(), getFrom()), not in the data map.

How the Android SDK uses it

  • Template. notificationType set to carousel shows a carousel (see Carousel payload reference). Any other value, or no notificationType, shows a standard notification.
  • Channel. The notification is posted on the channel named in channelId, or on swan_notifications when there is no channelId. The SDK doesn't check that the channel exists. On Android 8.0 and later the system shows nothing for a channel that doesn't exist on the device, so create any custom channel (see Notification channels) before a campaign uses it.
  • Image. On a standard push, the SDK downloads image and shows it as the large icon and as the expanded picture, scaled down to fit within 720 × 720 pixels. If the download fails, the notification shows text only. Carousel pushes show the card images instead.
  • Sound. default or no sound plays the channel's sound. silent (or none) plays no sound. Any other value plays res/raw/<name> (a file extension in the value is ignored), or the channel's sound if your app has no such resource. This applies to standard and carousel pushes. On Android 8.0 and later a channel decides the sound, so the SDK posts such a push on a channel derived from the one it would use, with the same importance and settings and that sound (or no sound): <channelId>__snd_<name> or <channelId>__silent. The SDK creates a derived channel the first time a push uses that sound and reuses it after that. A push with silent (or none) plays no sound and does not vibrate; a push with a custom sound keeps the vibration of its channel. A channel you created with its own sound keeps its sound.
  • Tap. A tap opens your launcher activity. Every key of the data map is attached to the launch intent as a string extra, plus messageId. Pass the intent to Swan.handleNotificationIntent(intent) (see Deep linking on tap). For a carousel card, the route extra holds the route of the card that was tapped. Once the user has moved through a manual carousel with its previous and next buttons, the intent carries only messageId and that card's route.
  • Empty push. A push with no title, no body and no route shows nothing.

Example: standard push

A standard push with an image, a route, a channel, and one key/value pair, as your app receives it in RemoteMessage.data:

{
  "title": "Weekend sale",
  "body": "Up to 40% off selected items",
  "defaultRoute": "/offers/weekend",
  "route": "/offers/weekend",
  "image": "https://cdn.example.com/push/weekend.jpg",
  "channelId": "swan_promotional",
  "keyValuePairs": "{\"offerId\":\"WKND40\"}"
}

Always present: title and body. Conditional in this example: defaultRoute and route (the campaign has a route; route isn't on every push), image (the template has an image), channelId (the template sets a channel) and keyValuePairs (the campaign has a key/value pair for Android). A template that sets a sound adds sound, for example "sound": "default".

iOS push payload reference

This is exactly what Swan sends to an iOS device running the Swan iOS SDK. Use it when you write your own Notification Service Extension or Content Extension, or when you read userInfo yourself.

Delivery

Every iOS push is sent through Firebase Cloud Messaging to the device's Firebase registration token (see Provider setup). Firebase forwards it to APNs with these headers:

APNs headerValue
apns-push-typealert
apns-priority10

The aps dictionary

KeyWhen presentValue
alertAlways{ "title": …, "body": … } from the template. Empty strings when the template has no title or body.
mutable-contentAlways1 — your Notification Service Extension runs for every Swan push.
soundUnless the template's sound is silent"default" when the template sets no sound or default. A custom sound name without a file extension gets .wav appended (chime → chime.wav); a name with an extension is sent as is. The file must be in your app bundle. When the template's sound is silent, sound is left out and the notification plays no sound.
categoryTemplate sets a category, or the push is a carouselThe template's category. A carousel push with no category set gets swan_carousel — see Custom Notification Content Extension for carousel.
badgeTemplate sets a badge countThe badge number.
interruption-levelTemplate sets oneThe template's interruption level: passive, active, time-sensitive, or critical.

Swan keys

These keys sit at the top level of userInfo, next to aps. All values are strings.

KeyWhen presentValue
titleAlwaysSame as aps.alert.title.
bodyAlwaysSame as aps.alert.body.
defaultRouteCampaign has a routeThe campaign's deep-link route. Some pushes also carry it as an empty string when the campaign has no route.
routeSome pushesSame value as defaultRoute. See How to read the tables for how to resolve the route.
imageTemplate has an imageImage URL. The same URL is also sent as fcm_options.image.
soundTemplate sets a soundThe template's sound value as entered (no .wav added, and silent is passed through).
keyValuePairsCampaign has key/value pairs for iOSJSON-encoded object of the pairs targeted at iOS or at both platforms, e.g. "{\"offerId\":\"WKND40\"}". Pairs targeted only at Android are left out.
notificationTypeCarousel push"carousel". Not present for standard pushes.
carouselModeCarousel push, when setmanual or auto — see Carousel payload reference.
carouselVariantCarousel push, when setstandard or filmstrip.
carouselItemsCarousel push with cardsJSON-encoded array of cards — see Card format.
oneLinkParamsCampaign has OneLink parametersJSON-encoded object — see OneLink keys.
oneLinkConfigCampaign has a OneLink configurationJSON-encoded object — see OneLink keys.
messageIdPush sent by the Swan platform with delivery receiptsThe Swan message id. The SDK reports it as PushNotificationReceivedPayload messageId.
dispatchIdPush sent by the Swan platform with delivery receiptsThis device's dispatch id, used by the SDK when it reports receipts.
swanReceiptPush sent by the Swan platform with delivery receiptsOpaque receipt token the SDK sends back when it reports the push as delivered or tapped (see Delivery and tap receipts). Don't parse it.

Firebase adds its own keys to userInfo as well (for example gcm.message_id, and fcm_options when the push has an image). Don't rely on the full list of Firebase keys; it is controlled by Firebase.

The SDK reads these keys for you: title, body, route / defaultRoute, and keyValuePairs are parsed into the NotificationOpenedPayload fields, and the other string keys (such as oneLinkParams and oneLinkConfig) arrive in extras. The PushNotificationReceivedPayload data map contains them all.

Example: standard push

A standard push with an image, a route, and one key/value pair, as your app receives it in userInfo:

{
  "aps": {
    "alert": {
      "title": "Weekend sale",
      "body": "Up to 40% off selected items"
    },
    "mutable-content": 1,
    "sound": "default"
  },
  "title": "Weekend sale",
  "body": "Up to 40% off selected items",
  "defaultRoute": "/offers/weekend",
  "route": "/offers/weekend",
  "image": "https://cdn.example.com/push/weekend.jpg",
  "keyValuePairs": "{\"offerId\":\"WKND40\"}",
  "fcm_options": {
    "image": "https://cdn.example.com/push/weekend.jpg"
  },
  "gcm.message_id": "1700000000000000"
}

Always present in every Swan iOS push: aps.alert, aps.mutable-content, title, and body. aps.sound is present unless the template's sound is silent. Conditional in this example: defaultRoute and route (the campaign has a route; route isn't on every push), image and fcm_options (the template has an image) and keyValuePairs (the campaign has an iOS key/value pair). gcm.message_id is added by Firebase, not by Swan.

For a carousel push, see the iOS carousel example.

Web push payload reference

Delivery

Swan sends web pushes with the Web Push protocol, signed with your VAPID keys, to the push subscription the browser created in Swan.subscribeToPush(). The message is a JSON object. The Swan service worker reads it with event.data.json() in its push handler.

The tables below describe web pushes sent by journeys. Web pushes sent by broadcasts currently have a different shape: the text is in message instead of body (so the Swan service worker shows an empty body), icon and image are left out when the template doesn't set them, and data holds only url and button.

Payload keys

KeyWhen presentValueWhat the Swan service worker does with it
titleAlwaysNotification title.Shows it as the notification title.
bodyAlwaysNotification body.Shows it as the notification body.
iconUsuallyIcon URL. An empty string when the template sets no icon.Shows it as the notification icon.
imageUsuallyImage URL. An empty string when the template sets no image.Nothing — the image is not displayed.
actionsAlwaysArray of buttons, each { "action": …, "title": …, "icon": … }. Empty array when the template has no buttons.Passes them to the browser as notification actions. A click on a button is handled the same way as a click on the notification.
data.urlAlwaysThe template's click-through URL.Nothing.
data.buttonAlwaysObject that maps each button's action to a URL, for example { "button_click_1": "https://…" }.Nothing.
data.commIdAlwaysSwan's ID for this message.Sends it with the delivery and click receipts, and passes it to your listeners as messageId.
data.CDIDAlwaysThe recipient's CDID.Sends it with the delivery and click receipts.

How the Swan service worker handles it

  • Push received. The service worker shows the notification with title, body, icon and actions, keeps the whole data object on the notification, and sends a delivery receipt to Swan.
  • Notification clicked. The service worker closes the notification, sends a click receipt to Swan, and passes { messageId, title, body, route, keyValuePairs } to every open tab of your site, where addNotificationOpenedListener receives it. messageId is data.commId. route comes from data.route or data.defaultRoute, and keyValuePairs from data.keyValuePairs. It then focuses the first open tab of your site. If no tab is open, it opens route.
  • What that means for a Swan web push today. The data object carries no route, defaultRoute or keyValuePairs, so your listener receives route: null and keyValuePairs: null, addDeepLinkOpenedListener does not fire, and a click when no tab of your site is open doesn't open a window. The service worker doesn't use data.url or data.button.

Example

A web push with an icon, an image, and one button, as event.data.json() returns it in the service worker:

{
  "title": "Weekend sale",
  "icon": "https://cdn.example.com/push/icon-192.png",
  "image": "https://cdn.example.com/push/weekend.jpg",
  "actions": [
    {
      "action": "button_click_1",
      "title": "Shop now",
      "icon": ""
    }
  ],
  "body": "Up to 40% off selected items",
  "data": {
    "url": "https://www.example.com/offers/weekend",
    "button": {
      "button_click_1": "https://www.example.com/offers/weekend",
      "button_click_2": ""
    },
    "commId": "5b1f0c3e-8a2d-4f6b-9e47-1c3d2a7f9b80",
    "CDID": "0e6c2f9a-41b7-4d3e-8f25-7a9b3c1d6e42"
  }
}

Always present: title, body, actions, and data with url, button, commId and CDID. icon and image hold URLs because the template sets them; otherwise they are empty strings.

Carousel pushes are sent to Android and iOS (not to web). A carousel push carries everything a standard push carries, plus these keys:

KeyValueValues the SDKs accept
notificationType"carousel"Any other value, or no notificationType, makes the push a standard push.
carouselModemanual or auto. Carousel templates created in the Swan dashboard use manual.auto shows an auto-advancing carousel. Any other value, or no carouselMode, is treated as manual.
carouselVariantstandard or filmstripfilmstrip shows the filmstrip layout. Any other value, or no carouselVariant, is treated as standard.
carouselItemsJSON-encoded array of cards — see Card format.A missing, empty, or unreadable value means the push has no cards.

There is no interval key. An auto carousel advances every 3 seconds on Android, and on iOS CarouselPayloadPublic.intervalMs is 3000.

Each card in carouselItems is an object with these four keys. Every card carries all four; a field the template leaves blank is an empty string.

FieldTypeValue
imageUrlstringCard image URL. Give every card an image: a card without one is skipped by the filmstrip layout, by the Android auto layout and by the React Native SDK, and shows an empty image slot in the native Android standard layout.
titlestringCard title.
bodystringCard text.
routestringRoute to open when this card is tapped. When it is empty, the push's defaultRoute is used.

The SDKs show at most the first 10 cards. An Android auto carousel uses at most the first 5.

Android

  • manual, standard — one card at a time, with its title and text, a position counter (for example 2 / 3), and previous and next buttons. A tap opens the route of the card on screen.
  • manual, filmstrip — the current card in the centre, with the previous and next cards as smaller previews on each side. Tapping a side preview moves to that card; tapping the centre card opens its route. Cards without an image are skipped; if only one card has an image, it is shown in the standard layout.
  • auto (two or more cards) — the cards advance automatically every 3 seconds. A tap opens the push's defaultRoute, or the first card's route when there is no defaultRoute. Per-card routes and carouselVariant are not used. With one card, the manual layout is used.
  • No cards — the native Android SDK shows a standard notification with the push's title and body. The React Native SDK shows nothing when no card has an image.

iOS

  • Your Notification Service Extension (see iOS — Rich pushes and extensions) shows the push's title and body with the image of the first card that has one, in both manual and auto mode. When the push has no title or body, the first card's title or text is used.
  • If a carousel notification arrives with no category, the SDK sets it to swan_carousel in your Notification Service Extension.
  • For a swipeable carousel, add a Notification Content Extension for the swan_carousel category (or the template's own category, when it sets one) and read the cards with Templates.parseCarousel(_:) — see Custom Notification Content Extension for carousel.
  • When your Content Extension records the tapped card, the tap opens that card's route and its click receipt carries itemIndex — see Tapped card.

The click receipt for a tap on a carousel card carries itemIndex: the card's 0-based position in carouselItems (0 is the first card, so the third card is 2). It is the card's position in the push, even when cards without an image are not shown. A tap on the notification itself, a tap on a standard push, and the delivery receipt carry no itemIndex.

On iOS the tapped card comes from your Notification Content Extension: write itemIndex in the click data it records — see Open the tapped card and report which card it was.

On Android, when the user taps a card in a manual carousel, the click the SDK sends to Swan includes which card it was. The card is identified by its position in carouselItems — the first card is 0, the third card is 2 — and the position stays the same even when the filmstrip layout skips a card without an image. A tap on the notification itself rather than on a card, a tap on an auto carousel, and a tap on a standard push are reported as clicks with no card. You don't need to do anything to enable this.

A manual carousel with three cards, as your app receives it in RemoteMessage.data:

{
  "title": "New this week",
  "body": "Swipe to see this week's picks",
  "defaultRoute": "/collections/new",
  "route": "/collections/new",
  "sound": "default",
  "channelId": "swan_promotional",
  "notificationType": "carousel",
  "carouselMode": "manual",
  "carouselVariant": "standard",
  "carouselItems": "[{\"imageUrl\":\"https://cdn.example.com/push/running-shoes.jpg\",\"title\":\"Running shoes\",\"body\":\"Now 30% off\",\"route\":\"/products/running-shoes\"},{\"imageUrl\":\"https://cdn.example.com/push/rain-jacket.jpg\",\"title\":\"Rain jacket\",\"body\":\"New colours in stock\",\"route\":\"/products/rain-jacket\"},{\"imageUrl\":\"https://cdn.example.com/push/day-backpack.jpg\",\"title\":\"Day backpack\",\"body\":\"Free delivery this week\",\"route\":\"\"}]"
}

The same carouselItems value, decoded:

[
  {
    "imageUrl": "https://cdn.example.com/push/running-shoes.jpg",
    "title": "Running shoes",
    "body": "Now 30% off",
    "route": "/products/running-shoes"
  },
  {
    "imageUrl": "https://cdn.example.com/push/rain-jacket.jpg",
    "title": "Rain jacket",
    "body": "New colours in stock",
    "route": "/products/rain-jacket"
  },
  {
    "imageUrl": "https://cdn.example.com/push/day-backpack.jpg",
    "title": "Day backpack",
    "body": "Free delivery this week",
    "route": ""
  }
]

The third card has no route, so tapping it opens the push's defaultRoute, /collections/new.

The same campaign as your app receives it in userInfo:

{
  "aps": {
    "alert": {
      "title": "New this week",
      "body": "Swipe to see this week's picks"
    },
    "mutable-content": 1,
    "sound": "default",
    "category": "swan_carousel"
  },
  "title": "New this week",
  "body": "Swipe to see this week's picks",
  "defaultRoute": "/collections/new",
  "route": "/collections/new",
  "sound": "default",
  "notificationType": "carousel",
  "carouselMode": "manual",
  "carouselVariant": "standard",
  "carouselItems": "[{\"imageUrl\":\"https://cdn.example.com/push/running-shoes.jpg\",\"title\":\"Running shoes\",\"body\":\"Now 30% off\",\"route\":\"/products/running-shoes\"},{\"imageUrl\":\"https://cdn.example.com/push/rain-jacket.jpg\",\"title\":\"Rain jacket\",\"body\":\"New colours in stock\",\"route\":\"/products/rain-jacket\"},{\"imageUrl\":\"https://cdn.example.com/push/day-backpack.jpg\",\"title\":\"Day backpack\",\"body\":\"Free delivery this week\",\"route\":\"\"}]",
  "gcm.message_id": "1700000000000001"
}

aps.category is swan_carousel because the template sets no category of its own. sound and aps.sound are there because the template's sound is default. There is no channelId on iOS. carouselItems decodes to the same array as in the Android example.

oneLinkParams and oneLinkConfig are JSON-encoded objects, sent to Android and iOS when the campaign has OneLink set up. The SDK doesn't act on them; it passes them to you unparsed — in extras on Android and iOS, and as top-level fields of the opened payload in React Native — see the deep linking guide.

oneLinkParams:

FieldValue
baseUrlOneLink base URL from the campaign's OneLink settings.
appIdApp ID from the campaign's OneLink settings.
cdidThe recipient's CDID.
runIdID of the journey run that sent the push.
campaignNameCampaign name from the campaign's OneLink settings, or the journey's name when they set none.
campaignIdCampaign ID from the campaign's OneLink settings, or the journey's ID when they set none.
channelpush unless the campaign's OneLink settings set another value.
campaignTypejourney unless the campaign's OneLink settings set another value.

oneLinkConfig:

FieldValue
deepLinkEnabledBoolean from the campaign's OneLink settings.
deepLinkValueString from the campaign's OneLink settings.
deepLinkSub1String from the campaign's OneLink settings.

Payload for older SDK versions

The current Android, iOS and React Native SDKs all register for the payloads above. A device registered by an older SDK version that doesn't register for data-only delivery can instead receive a standard FCM notification message: a notification block with the title, body and image, and a data map that holds only route (an empty string when the campaign has no route). The operating system displays it. Channels, custom sounds, carousels, key/value pairs and OneLink keys are not sent. On iOS, when the push has an image, aps.mutable-content is 1 and fcm_options.image carries the image URL.


Troubleshooting

SymptomLikely cause
Permission granted but no notifications arrivePush token didn't register — grep for [SwanSDK] Device registered successfully. On iOS, also check that Swan.shared.getPushToken() returns a Firebase registration token, not a 64-character hex APNs token (see Provider setup).
Notification never appears on Android 8.0+The campaign's channelId names a channel that doesn't exist on the device, and Android shows nothing for an unknown channel. Create the channel first (see Notification channels) or use one of the five default Swan channels.
Notification arrives but tap doesn't fire the listenerMissing Swan.handleNotificationIntent(intent) call in onCreate/onNewIntent (Android)
Carousel notification truncates imagesAndroid 13 RemoteViews 2 MB parcel limit — fixed in Android SDK v1.0.0; reproducible on devices that never updated past app v2.6.x
A push you expected to be silent shows a notificationThe Android, React Native and Web SDKs suppress the notification only when the push's data has silent set to "true"; the iOS SDK has no silent flag. Swan campaigns don't send silent (see the push payload reference).
React Native on Android: several pushes sent at once to a closed app, only the first is shownA known issue on React Native 0.76 or later with the new architecture, when the app is fully closed. Nothing is needed for normal sending; see Troubleshooting.

Reference

On this page