> ## Documentation Index
> Fetch the complete documentation index at: https://docs.appdna.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# React Native Push Notifications

> Token registration, delivery and tap tracking

> [!NOTE]
>
> **Supported on:** iOS SDK `1.0.70+` · Android SDK `1.0.42+` · React Native SDK `1.0.7+` (New Architecture only)

The AppDNA React Native SDK provides a complete push notification module for registering device tokens, tracking delivery and taps, and handling notification interactions through delegates and event listeners.

## Platform Setup

Before using push notifications, configure the native push services for each platform:

### iOS

1. In Xcode, enable the **Push Notifications** capability under your target's **Signing & Capabilities** tab.
2. Generate an APNs authentication key (.p8 file) in the [Apple Developer Portal](https://developer.apple.com/account/resources/authkeys/list).
3. In the AppDNA Console under **Settings > Push**, in the **APNs (iOS)** card, paste the contents of the .p8 file into **P8 Auth Key**, fill in **Key ID**, **Team ID** and **Bundle ID**, pick the **Environment**, and click **Save**.

### Android

1. Add your `google-services.json` file to the `android/app` directory.
2. Upload your Firebase **service-account JSON** to the AppDNA Console under **Settings > Push**, in the **FCM (Android)** card (paste it into **Service Account JSON**), enter your Firebase **Project ID** (the `project_id` in that JSON), and click **Save**. It must be a service-account key (`"type": "service_account"`, with `client_email` and `private_key`); other Google credential types, such as a workload identity federation configuration, are refused.

> [!WARNING]
>
> Without the platform-specific push credentials uploaded to the Console, push notifications will not be delivered to your users.

> [!NOTE]
>
> **Requires:** delivered / tapped tracking, `AppDNA.push.handleMessage` / `handleTap` and tap routing need an AppDNA server from the release that ships React Native SDK 1.0.19 or later — older servers sent no `push_id`. AppDNA pushes carry the marker `appdna: "1"` in their data; the SDK handles only marked messages and ignores every other push.

## How push works on iOS

> [!NOTE]
>
> Requires React Native SDK 1.0.19+.

The SDK installs a notification-centre delegate proxy automatically at app launch, right after `application(_:didFinishLaunchingWithOptions:)` returns. It wraps whatever delegate exists at that moment, so a delegate set in `didFinishLaunching` is wrapped. RNFirebase and notifee install their own delegate at that same moment, so the order is not fixed: AppDNA may wrap them, or they may wrap AppDNA. Each keeps the delegate it replaced and forwards to it, so either order works. A delegate assigned later replaces the proxy and cannot be re-wrapped (the proxy installs once per launch): set it in `didFinishLaunching` instead, or forward AppDNA pushes from it with `handleMessageData` / `handleNotificationTap` as shown under **Opt out** below. The proxy does not change how your own notifications are presented or handled, unless you set `AppDNAForegroundPresentation` (see the trade-off below). AppDNA pushes are tracked and routed by AppDNA, including the **cold-start tap** — no forwarding and no AppDelegate code is needed.

* RNFirebase and notifee do not surface AppDNA pushes at all, so your own handlers never see them.
* Delivered tracking covers **foreground** delivery only, on iOS and on Android (in the background FCM displays AppDNA pushes itself); background delivery is not tracked. The tap is still tracked when the app opens, on both platforms automatically (on Android see [Taps on Android](#taps-on-android)).
* **Foreground presentation.** When a push library such as RNFirebase ends up as the outer notification delegate, it keeps deciding how notifications are shown in the foreground, and AppDNA's foreground delivered tracking does not run — unless `AppDNAForegroundPresentation` is set or the delegate AppDNA wrapped implements `willPresent`. To have AppDNA pushes presented and tracked in the foreground, set the Info.plist key `AppDNAForegroundPresentation` to an array of `banner`, `list`, `sound`, `badge` (an empty array = do not present). Trade-off: when AppDNA ends up innermost with no previous delegate, your own FCM pushes are then **not** presented in the foreground — leave the key unset if that matters more.
* **Opt out** with the Info.plist key `AppDNADisableNotificationProxy` = `YES`, then forward from your own native `UNUserNotificationCenterDelegate`:

```swift theme={null}
// willPresent
AppDNA.pushModule.handleMessageData(notification.request.content.userInfo)
// didReceive
AppDNA.pushModule.handleNotificationTap(response.notification.request.content.userInfo,
                                        actionIdentifier: response.actionIdentifier)
```

* If your build drops the SDK's launch hook (aggressive dead-stripping), you can call the native iOS `installNotificationProxy()` from Swift **after** you set your own `center.delegate`. It installs the proxy only if it is not installed yet; once installed, the call does nothing and cannot re-wrap a delegate assigned later:

```swift theme={null}
AppDNA.installNotificationProxy()
```

## Taps on Android

The module hands every tap intent to the native Android SDK's `handlePushTap(intent)`: the activity's intent when you call `configure` (a tap that launched the app), every intent it receives afterwards (`onNewIntent`), and the current activity's intent whenever the app resumes (a tap that started a new activity while React Native kept running, for example after the activity was closed with Back). That covers body, button and text-reply taps on notifications the SDK displayed, which no JS push library sees, and taps on notifications FCM displayed. Once the SDK is configured, the tap is tracked, routed and passed to `onPushTapped`, once. The module hands the native SDK a copy of the intent, so the activity's intent keeps its extras (`appdna`, `push_id`, `delivery_id` and the rest): if your JS reads them and calls `AppDNA.push.isAppDNAMessage(data)` or `AppDNA.push.handleTap(data)`, the tap is still recognised as AppDNA's, and `handleTap` returns `true` without tracking or routing it again. The tap is tracked and routed once: the module hands each intent to the native SDK once (calling `configure` again, or a reload, does not re-run the launch intent), and the SDK remembers the taps it has handled (the last 32, keyed by `delivery_id`, else `push_id`), so the same tap forwarded through `AppDNA.push.handleTap` is not tracked again either.

Set the push delegate (`AppDNA.push.setDelegate`) before you call `configure`. The cold-start tap is handed over as soon as `configure` finishes, and a tap that arrives while no delegate is set is still tracked and routed, but it does not reach `onPushTapped`.

**A tap that restores the app after Android killed its process** reaches `MainActivity.onNewIntent` before React Native is running, and React Native drops it. To keep it, store it as the activity's intent, so the module finds it at `configure`:

```kotlin theme={null}
// android/app/src/main/java/.../MainActivity.kt
override fun onNewIntent(intent: Intent) {
  super.onNewIntent(intent)
  setIntent(intent)
}
```

## If your app already uses Firebase Messaging

> [!NOTE]
>
> Requires React Native SDK 1.0.19+.

If your app registers its own Firebase Messaging handler (for example with `@react-native-firebase/messaging`), keep it as the only handler and forward AppDNA messages to the SDK:

1. **Android — remove the SDK's messaging service.** Android delivers each message to one `FirebaseMessagingService` only. In `android/app/src/main/AndroidManifest.xml` (with `xmlns:tools="http://schemas.android.com/tools"` on `<manifest>`):

```xml theme={null}
<service android:name="ai.appdna.sdk.integrations.AppDNAMessagingService" tools:node="remove"/>
```

or, in `android/app/src/main/res/values/bools.xml`:

```xml theme={null}
<bool name="appdna_messaging_service_enabled">false</bool>
```

2. Keep `@react-native-firebase/messaging` as your only handler.
3. **Pass the right token per platform.** AppDNA sends iOS pushes directly over APNs.

```typescript theme={null}
import { Platform } from 'react-native';
import messaging from '@react-native-firebase/messaging';

async function registerPushToken() {
  if (Platform.OS === 'ios') {
    // iOS: the APNs token — never getToken() (the FCM token) on iOS.
    const t = await messaging().getAPNSToken(); // null until iOS has registered with APNs
    if (t) { await AppDNA.setPushToken(t); }
  } else {
    // Android: the FCM token.
    const t = await messaging().getToken();
    if (t) { await AppDNA.setPushToken(t); }
  }
}

// After configure, again after requestPermission() resolves, and on every app start.
await registerPushToken();
// onTokenRefresh reports FCM tokens only — use it on Android; iOS re-reads getAPNSToken() at start.
messaging().onTokenRefresh(async (token: string) => {
  if (Platform.OS === 'android') await AppDNA.setPushToken(token);
});
```

**Never pass the FCM token (`getToken()`) on iOS**: the SDK rejects it with `BAD_TOKEN` and every iOS push then fails.

4. **Forward AppDNA messages (Android).** iOS is automatic (above).

```typescript theme={null}
import messaging from '@react-native-firebase/messaging';

messaging().onMessage(async (message: { data?: Record<string, string> }) => {
  const data = message.data ?? {};
  if (await AppDNA.push.isAppDNAMessage(data)) {
    await AppDNA.push.handleMessage(data); // tracks delivered, fires onPushReceived; never displays
  }
  // ...your own handling of your own messages
});
```

Display is unaffected: AppDNA pushes carry a `notification` block, which FCM displays in the background.

5. **Forward taps (Android).** Optional: the module already hands every tap intent to the native SDK ([Taps on Android](#taps-on-android)). Forwarding as well is safe, because each tap is tracked once.

```typescript theme={null}
import messaging from '@react-native-firebase/messaging';

messaging().onNotificationOpenedApp(async (message: { data?: Record<string, string> }) => {
  await AppDNA.push.handleTap(message.data ?? {});
});
const initial = await messaging().getInitialNotification();
if (initial) await AppDNA.push.handleTap(initial.data ?? {});
```

Every forwarding call returns `false` and does nothing for a non-AppDNA message, and each message is tracked once, so forwarding everything is safe. **Do not also call `trackPushDelivered` / `trackPushTapped`** for these messages — they carry no `delivery_id` and would double-count.

> [!NOTE]
>
> **Known limitation:** a message that arrives while the app is in the background is handled by RNFirebase's `setBackgroundMessageHandler`; FCM still displays the notification and the tap is tracked when the app opens ([Taps on Android](#taps-on-android)). Forwarding **delivered** from the background handler is not supported in this release.

## Static Methods

The `AppDNA` class exposes top-level static methods for common push operations:

### Set Token

Pass a device push token to the SDK manually:

```typescript theme={null}
await AppDNA.setPushToken("device-token-string");
```

### Set Permission Status

Update the SDK with the current push permission status:

```typescript theme={null}
await AppDNA.setPushPermission(true);
```

### Track Delivery

Track delivery manually — **only for pushes the SDK does not see.** These calls carry no `delivery_id`, so combined with forwarding (`AppDNA.push.handleMessage`) or the iOS automatic handler they double-count:

```typescript theme={null}
await AppDNA.trackPushDelivered("push-123");
```

### Track Tap

Track a tap manually, with an optional action identifier — **only for pushes the SDK does not see** (same caveat as above):

```typescript theme={null}
await AppDNA.trackPushTapped("push-123", "open_workout");
```

## Push Module

Access the push module through the `AppDNA.push` property for advanced usage:

```typescript theme={null}
const push = AppDNA.push;
```

### Module Methods

| Method | Signature | Description |
| - | - | - |
| `setToken` | `setToken(token: string): Promise<void>` | Register a device push token |
| `setPermission` | `setPermission(granted: boolean): Promise<void>` | Update the push permission status |
| `trackDelivered` | `trackDelivered(pushId: string): Promise<void>` | Track delivery manually — only for pushes the SDK does not see (no `delivery_id`; double-counts with forwarding) |
| `trackTapped` | `trackTapped(pushId: string, action?: string): Promise<void>` | Track a tap manually — only for pushes the SDK does not see |
| `isAppDNAMessage` | `isAppDNAMessage(data: Record<string, unknown>): Promise<boolean>` | Whether a message's data is an AppDNA push (`appdna: "1"`) |
| `handleMessage` | `handleMessage(data: Record<string, unknown>): Promise<boolean>` | Forward a received message (Android): tracks delivered, fires `onPushReceived`, never displays |
| `handleTap` | `handleTap(data: Record<string, unknown>, actionId?: string): Promise<boolean>` | Forward a tap: tracks it, fires `onPushTapped`, routes the AppDNA action |
| `requestPermission` | `requestPermission(): Promise<boolean>` | Request push permission from the user |
| `getToken` | `getToken(): Promise<string \| null>` | Returns the current device token, or null |
| `setDelegate` | `setDelegate(delegate: Partial<AppDNAPushDelegate> \| null): void` | Set a delegate for push notification callbacks. Pass `null` to clear. |

> [!NOTE]
>
> **Pass the marker as a string.** AppDNA's servers send `appdna` and `push_id` as strings (`"1"`, `"…"`). FCM `data` values are always strings, so this matters only for a payload you build or rewrite yourself. Keep them strings: iOS reads only string values, so a numeric `appdna: 1` is not an AppDNA push there, while the Android bridge converts a number to its string (`1` → `"1"`) and accepts it — the two platforms would disagree.

### Request Permission

Request push notification permission from the user. This presents the system permission dialog:

```typescript theme={null}
const granted = await AppDNA.push.requestPermission();

if (granted) {
  console.log("Push permission granted");
} else {
  console.log("Push permission denied");
}
```

### Get Current Token

Retrieve the current device push token:

```typescript theme={null}
const token = await AppDNA.push.getToken();
if (token) {
  console.log("Current token:", token);
}
```

## AppDNAPushDelegate

Set a delegate to receive push notification lifecycle callbacks:

```typescript theme={null}
interface AppDNAPushDelegate {
  onPushTokenRegistered(token: string): void;
  onPushReceived(notification: Record<string, unknown>, inForeground: boolean): void;
  /** `actionId` is `undefined` when the user tapped the body rather than an action button. */
  onPushTapped(notification: Record<string, unknown>, actionId: string | undefined): void;
}
```

**Action buttons and custom sound** (set on the Console's push compose page) are displayed by the native SDKs. The rules are in [iOS push](https://docs.appdna.ai/sdks/ios/push.md#action-buttons-and-custom-sound) and [Android push](https://docs.appdna.ai/sdks/android/push.md#action-buttons-and-custom-sound). On iOS, add a Notification Service Extension whose class subclasses `NotificationService` from the extension-safe `AppDNANotificationExtension` pod (`pod 'AppDNANotificationExtension'` in the extension's target block of your `ios/Podfile`; make it a top-level target, not one nested in the app's target, which would inherit the app's pods into the extension, or add `inherit! :none` to a nested one), so a new button set shows its buttons on the first push. Your `ios/Podfile` needs `use_frameworks!`, dynamic or `:linkage => :static`: the iOS SDK cannot be built from pods built as static libraries ([iOS installation](https://docs.appdna.ai/sdks/ios/installation.md#cocoapods)). On Android, buttons appear only on notifications the native SDK builds itself. A push that FCM or your own Firebase Messaging handler displays has none. A button tap arrives as `onPushTapped(notification, actionId)` with the button's id. The typed text of a text-reply button is in `notification.data.reply_text`.

### Example Implementation

```typescript theme={null}
declare function showBanner(title: unknown, body: unknown): void;
declare function handleAction(actionId: string): void;

AppDNA.push.setDelegate({
  onPushTokenRegistered(token: string) {
    console.log('Token registered:', token);
  },

  onPushReceived(notification: Record<string, unknown>, inForeground: boolean) {
    if (inForeground) {
      // The notification map uses the snake_case keys native sends.
      showBanner(notification.title, notification.body);
    }
  },

  onPushTapped(notification: Record<string, unknown>, actionId: string | undefined) {
    if (actionId) {
      // Handle custom action
      handleAction(actionId);
    }
  },
});
```

## Standalone AppDNAPush Class

For a more React-idiomatic approach, use the standalone `AppDNAPush` class with callback-based listeners:

```typescript theme={null}
import { AppDNAPush } from '@appdna-ai/react-native-sdk';
```

### Methods

| Method | Signature | Description |
| - | - | - |
| `requestPermission` | `requestPermission(): Promise<boolean>` | Request push permission from the user |
| `onPushReceived` | `onPushReceived(cb: (payload: PushPayload, inForeground: boolean) => void): () => void` | Listen for received notifications |
| `onPushTapped` | `onPushTapped(cb: (payload: PushPayload, actionId?: string) => void): () => void` | Listen for notification taps |

### Example with Listeners

```typescript theme={null}
import { AppDNAPush } from '@appdna-ai/react-native-sdk';

declare function navigateTo(target: string): void;

// Request permission
const granted = await AppDNAPush.requestPermission();

// Listen for received push notifications
const unsubReceived = AppDNAPush.onPushReceived((payload, inForeground) => {
  console.log('Push received:', payload.title, inForeground);
});

// Listen for push notification taps. The payload keys are snake_case.
const unsubTapped = AppDNAPush.onPushTapped((payload, actionId) => {
  console.log('Push tapped:', payload.push_id, actionId);
  if (payload.action_value) {
    navigateTo(payload.action_value);
  }
});

// Clean up listeners when component unmounts
unsubReceived();
unsubTapped();
```

> [!WARNING]
>
> Always call the unsubscribe function returned by `onPushReceived` and `onPushTapped` when the component unmounts to prevent memory leaks.

## PushPayload

The `PushPayload` type contains the notification content. **The keys are snake\_case** — they are the
keys native puts on the wire, not camelCase:

| Property | Type | Description |
| - | - | - |
| `push_id` | `string` | Unique identifier for the notification |
| `title` | `string` | Notification title |
| `body` | `string` | Notification body text |
| `image_url` | `string \| undefined` | URL to a rich notification image |
| `data` | `Record<string, string> \| undefined` | Custom data payload |
| `action_type` | `string \| undefined` | Action type (e.g., "deep\_link", "url") |
| `action_value` | `string \| undefined` | Action value (e.g., a URL or screen ID) |
| `actions` | `PushAction[] \| undefined` | The registered action buttons — look up the tapped `actionId` here |

Each entry in `actions` is a `PushAction`:

| Property | Type | Description |
| - | - | - |
| `id` | `string` | Button identifier — matches `actionId` in `onPushTapped` |
| `label` | `string` | Button label as displayed |
| `action_type` | `string` | Action type (e.g., "deep\_link", "url") |
| `action_value` | `string \| undefined` | Action value (e.g., a URL or screen ID) |

## Native events

Native emits the following to the push delegate:

| Event | Payload | Triggered When |
| - | - | - |
| `onPushTokenRegistered` | `{ token: string }` | Device token is successfully registered |
| `onPushReceived` | `{ payload: PushPayload, inForeground: boolean }` | A push notification is received |
| `onPushTapped` | `{ payload: PushPayload, actionId?: string }` | User taps on a push notification |

> [!NOTE]
>
> Use `AppDNAPush` or `AppDNA.push.setDelegate(...)`. There is no supported way to subscribe to these
> events directly, and a `NativeEventEmitter` subscription would never fire.

## Auto-Tracked Events

The SDK tracks the following push-related events for **AppDNA pushes** it sees — through the Android messaging service, the iOS automatic handler, or your forwarding calls:

| Event | Triggered When |
| - | - |
| `push_token_registered` | Device token is successfully registered |
| `push_permission_granted` | User grants push permission |
| `push_permission_denied` | User denies push permission |
| `push_delivered` | An AppDNA push is delivered while the app is in the foreground (carries `delivery_id`); background delivery is not tracked on either platform |
| `push_tapped` | User taps an AppDNA push (carries `delivery_id`) |
| `push_dismissed` | The user swipes an AppDNA push away without opening it (carries `push_id`, and `delivery_id` when the push has one) |

> [!NOTE]
>
> `push_dismissed` reports the SAME properties on both platforms, so one query reads both. On iOS it
> requires the notification's category to be registered with `.customDismissAction`, which the SDK
> does for every AppDNA push; Android reports it from the notification's delete intent. There is no
> server endpoint for a dismissal — unlike delivered and tapped, it is an analytics event only.

> [!NOTE]
>
> You do not need to track these events yourself. Pushes that are not AppDNA pushes are never tracked, and `onPushReceived` / `onPushTapped` do not fire for them.

## Full Example

```tsx theme={null}
import React, { useEffect } from 'react';
import { AppDNA, AppDNAPush } from '@appdna-ai/react-native-sdk';

declare function showInAppBanner(notification: Record<string, unknown>): void;
declare function handleDeepLink(
  notification: Record<string, unknown>,
  actionId: string | undefined,
): void;
declare function MainNavigator(): React.ReactElement;

function App() {
  useEffect(() => {
    async function setupPush() {
      // Set the delegate first, so a tap that launched the app reaches onPushTapped
      AppDNA.push.setDelegate({
        onPushTokenRegistered(token) {
          console.log("Token:", token);
        },
        onPushReceived(notification, inForeground) {
          if (inForeground) {
            showInAppBanner(notification);
          }
        },
        onPushTapped(notification, actionId) {
          handleDeepLink(notification, actionId);
        },
      });

      // Configure the SDK
      await AppDNA.configure('adn_live_xxx', 'production');

      // Request permission
      const granted = await AppDNA.push.requestPermission();
      console.log("Push permission:", granted);
    }

    void setupPush();
  }, []);

  // Listener-based approach for component-scoped handling
  useEffect(() => {
    const unsubReceived = AppDNAPush.onPushReceived((payload) => {
      console.log('Received:', payload.title);
    });

    const unsubTapped = AppDNAPush.onPushTapped((payload) => {
      console.log('Tapped:', payload.push_id);
    });

    return () => {
      unsubReceived();
      unsubTapped();
    };
  }, []);

  return <MainNavigator />;
}
```

## Scheduled pushes in the user's time zone

A campaign scheduled with **Send in user's timezone** reaches each user when their own clock shows the scheduled date and time. Each user gets it once, at the first check (every minute) that finds their local time has reached it — also when a daylight-saving change or a move to another zone happens while the campaign is going out. The audience is fixed when the campaign starts going out, in the first zone to reach the time. From React Native SDK 1.0.19, every event the SDK sends carries the device's time zone (its IANA name, read by the native SDK), and AppDNA keeps the latest one on the identified user's profile — so you need no code for this. Push quiet hours and journey waits that end at a time of day use the same zone.

The zone is resolved in this order:

1. the `timezone` trait your app passes to `identify` (an IANA name such as `Europe/Berlin`), if you set one — it always takes precedence, and the device's zone never overwrites it;
2. the zone the user's device last reported;
3. the app's time zone;
4. UTC.

A value that is not an IANA zone name is ignored at each step. The device's zone is recorded for identified users only (after `identify`), from their next event. Set the trait only when the zone your app knows for the user should win over the device's — for example a zone the user picked in your settings:

```typescript theme={null}
await AppDNA.identify('user-123', { timezone: 'Europe/Berlin' }); // the zone the user chose in your app
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.