> For the complete documentation index, see [llms.txt](https://docs.metica.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.metica.com/api/react-native-sdk.md).

# React Native SDK

The Metica Ads SDK for React Native ([`@metica/react-native-sdk`](https://www.npmjs.com/package/@metica/react-native-sdk)) brings Metica's ad optimization to React Native apps on Android and iOS. It is a thin layer over the native [Android SDK](https://docs.metica.com/api/android-sdk.md) and [iOS SDK](https://docs.metica.com/api/ios-sdk.md), and it keeps the public API of the AppLovin MAX React Native plugin, [`react-native-applovin-max`](https://github.com/AppLovin/AppLovin-MAX-React-Native) 9.6.0: the same module objects, method names, listeners, enums and payload types.

Metica initializes AppLovin MAX for you and runs the ad waterfall: an optimized one for users in the trial group, and plain MAX for users in the holdout group. If your app already uses `react-native-applovin-max`, moving to Metica is mostly a change of import and of the `initialize` call; see [Migrating from react-native-applovin-max](#migrating-from-react-native-applovin-max).

## What you need <a href="#what-you-need" id="what-you-need"></a>

To use the Metica React Native SDK you need:

* An `API key`, obtainable in the Metica platform.
* An `appId`, obtainable in the Metica platform.
* A `MAX SDK Key`, obtainable from the [AppLovin dashboard](https://dash.applovin.com/o/account?r=3#keys) under "SDK Key".
* Your AppLovin MAX ad unit ids for interstitial and rewarded ads. They differ per platform.

## Requirements

| Area               | Requirement                                                                                                                                                                                                  |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| React Native       | **0.77 or later**, with the **New Architecture** (Turbo Modules, the default since 0.76). The legacy architecture is not supported. Tested with 0.77 and 0.86.                                               |
| Android            | `minSdkVersion` 24, JDK 17, Kotlin 2.0 or later in the app's Android build (React Native 0.77's default; the native Metica SDK is built with Kotlin 2.1, which Kotlin 1.9 can't read).                       |
| iOS                | iOS 15.1 or later (React Native's minimum; the native Metica framework needs iOS 15.0), CocoaPods.                                                                                                           |
| Xcode              | Xcode 26.1 or later (the bundled iOS SDK 2.5.5 is built with it).                                                                                                                                            |
| Native Metica SDKs | Android `com.metica:metica-sdk` **2.5.4** (from Maven Central) and iOS `MeticaSDKFramework` **2.5.5** (bundled in the package).                                                                              |
| AppLovin MAX SDK   | Android `com.applovin:applovin-sdk` 13.0.1, the native Metica SDK's minimum. A newer 13.x version requested by your app or another plugin takes precedence. iOS: the `AppLovinSDK` pod, `>= 13.0.1, < 14.0`. |

Expo Go isn't supported, because the package contains native code. Expo apps need a development build.

{% hint style="warning" %}
Metica initializes the AppLovin MAX SDK itself. Don't initialize MAX before Metica. If your app also uses `react-native-applovin-max` for ad formats Metica doesn't cover, initialize Metica first; see [Using react-native-applovin-max alongside](#using-react-native-applovin-max-alongside).
{% endhint %}

## Dependencies

The package includes the native Metica SDK and the AppLovin MAX SDK, so your app doesn't add either of them. Mediation network adapters are not included: add the AppLovin MAX adapters for the networks you use, as described in AppLovin's [Preparing Mediated Networks](https://support.applovin.com/en/max/react-native/preparing-mediated-networks) guide. Use adapter versions that support AppLovin MAX SDK 13.x, the version range of the native Metica SDKs.

* **Android:** add the adapters to the dependencies in `android/app/build.gradle`, and the values your networks require to `android/app/src/main/AndroidManifest.xml`.
* **iOS:** add the adapter pods to `ios/Podfile`, and the keys your networks require to `ios/<YourApp>/Info.plist`. List your networks' SKAdNetwork identifiers under `SKAdNetworkItems`, as described in AppLovin's [SKAdNetwork](https://support.applovin.com/en/max/react-native/overview/skadnetwork) documentation.

For example, Google bidding and Google AdMob require your AdMob app id: in `AndroidManifest.xml` as the `com.google.android.gms.ads.APPLICATION_ID` meta-data value, and in `Info.plist` as `GADApplicationIdentifier`.

{% hint style="warning" %}
Some networks crash the app when a value they require is missing. The Google Mobile Ads SDK, for example, crashes without its app id.
{% endhint %}

## Supported Ad Formats

| Format           | Status                        |
| ---------------- | ----------------------------- |
| **Interstitial** | Supported: `InterstitialAd`   |
| **Rewarded**     | Supported: `RewardedAd`       |
| **Banner**       | Not supported in this release |
| **MREC**         | Not supported in this release |
| **App Open**     | Not a Metica format           |
| **Native**       | Not a Metica format           |

{% hint style="info" %}
Banners and MRECs are not supported in this release, so there is no `BannerAd`, `MRecAd` or `<AdView>`. If your app needs them, or app open or native ads, install `react-native-applovin-max` alongside Metica and use it for those formats only; see [Using react-native-applovin-max alongside](#using-react-native-applovin-max-alongside). Those ads run as plain MAX ads, outside Metica's optimization and reporting.
{% endhint %}

## Installation <a href="#installation" id="installation"></a>

Add the package to your app:

{% tabs %}
{% tab title="npm" %}

```bash
npm install @metica/react-native-sdk
```

{% endtab %}

{% tab title="Yarn" %}

```bash
yarn add @metica/react-native-sdk
```

{% endtab %}
{% endtabs %}

Then install the iOS pods:

```bash
cd ios && bundle exec pod install
```

* **Android:** Gradle fetches the native Metica SDK and the AppLovin SDK from Maven Central, which React Native projects already list in their repositories.
* **iOS:** the native Metica framework ships inside the package. CocoaPods adds the `AppLovinSDK` pod.

Then add the mediation adapters for your networks, as described in [Dependencies](#dependencies).

{% hint style="info" %}
Moving over from `react-native-applovin-max`? Read [Migrating from react-native-applovin-max](#migrating-from-react-native-applovin-max) first: you can remove the MAX plugin, or keep it for the formats Metica doesn't cover.
{% endhint %}

## Initialization

Initialize the SDK once, as early as possible in your app's lifecycle and before loading any ads, with `Metica.initialize`. `Metica` is the package's default export and is also exported by name.

`Metica.initialize` takes an `InitializationConfig`:

| Field       | Required | Description                                                                                                                                                         |
| ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apiKey`    | Yes      | Your Metica API key.                                                                                                                                                |
| `appId`     | Yes      | Your Metica app id.                                                                                                                                                 |
| `maxSdkKey` | Yes      | Your AppLovin MAX SDK key.                                                                                                                                          |
| `userId`    | No       | Your id for the current user. Takes precedence over `Metica.setUserId`. If neither is set (or you pass an empty string), the SDK generates one for the app install. |

Set the user's privacy choices **before** you initialize; see [Privacy and Consent](#privacy-and-consent).

{% code title="initializeMetica.ts" %}

```typescript
import Metica, { Privacy } from '@metica/react-native-sdk';

export async function initializeMetica(): Promise<void> {
  // Privacy settings first: the SDK reads them at initialization
  Privacy.setHasUserConsent(true);
  Privacy.setDoNotSell(false);

  try {
    const configuration = await Metica.initialize({
      apiKey: '<metica-api-key>',
      appId: '<metica-app-id>',
      maxSdkKey: '<applovin-max-sdk-key>',
      userId: 'user-id', // Optional: the SDK generates one if empty
    });

    // These values are useful only for your analytics
    console.log(`Current user is part of ${configuration.userGroup}`);
    console.log(`Forced holdout: ${configuration.isForcedHoldout}`);
    console.log(`User ID: ${configuration.userId}`);

    // Now you can load ads
  } catch (error) {
    // A blank apiKey, appId or maxSdkKey, or a native failure.
    // initialize() can be called again after a failure.
    console.error('Metica initialization failed', error);
  }
}
```

{% endcode %}

### Initialization response

`Metica.initialize` resolves with a `Configuration`:

* `userGroup`: the experiment group assigned to the current user, `'TRIAL'` or `'HOLDOUT'` (`null` if the native SDK reported none).
* `isForcedHoldout`: `true` when the user was assigned to the holdout group because of a problem, for example a connection issue.
* `isSuccess`: `false` when the user is in a forced holdout, or when the native SDK reported no group assignment.
* `userId`: the user id Metica uses. If you didn't provide one, this is the id the SDK generated.
* `countryCode` and `consentFlowUserGeography`: as in MAX's `Configuration`.
* `cmpFlowError`: present only when you enabled the terms and privacy policy flow; `null` means the flow completed, or that it didn't run because the MAX plugin initialized AppLovin first. See [Terms and privacy policy flow](#terms-and-privacy-policy-flow).

{% hint style="danger" %}
`userGroup`, `isForcedHoldout` and `isSuccess` are provided **for analytics and logging only**. You don't need to branch your code or add fallback logic on them: the SDK handles the experiment assignment and the holdout behavior internally, and you load and show ads the same way for every user.
{% endhint %}

{% hint style="info" %}
`initialize` is safe to call more than once: later calls return the same promise. If initialization fails, the promise rejects and you can call `initialize` again. After a JavaScript reload, `initialize` resolves with the result of the first initialization, because the native SDK stays initialized for the life of the app process.
{% endhint %}

### Analytics-only initialization

If you want Metica's [analytics](#analytics-metica-only) without ads, initialize with `Metica.initializeAnalytics`. It takes `apiKey`, `appId` and an optional `userId`, and resolves when analytics are ready. A later `Metica.initialize` adds ads and keeps the user id of the first call.

```typescript
await Metica.initializeAnalytics({
  apiKey: '<metica-api-key>',
  appId: '<metica-app-id>',
});
```

## Ad implementation

The SDK supports interstitial and rewarded ads, through the `InterstitialAd` and `RewardedAd` modules.

Like `react-native-applovin-max`, the SDK reports results through listeners, not return values: `loadAd` and `showAd` return nothing, and the outcome arrives in the loaded, load-failed, displayed and other listeners.

* There is **one listener per event and format**. Adding a listener replaces the previous one for that event, and `remove…Listener()` takes no argument.
* Listeners are per **format**, not per ad unit. See [Ad unit ids in events](#ad-unit-ids-in-events).
* Register your listeners once, for example at app start, and load ads after `Metica.initialize` has resolved.
* An exception thrown in a listener reaches React Native's error handling, as in `react-native-applovin-max`.

### Interstitial Ads

Full-screen ads that are shown between content transitions.

{% code title="interstitial.ts" %}

```typescript
import { Platform } from 'react-native';
import { InterstitialAd } from '@metica/react-native-sdk';

const INTERSTITIAL_AD_UNIT_ID =
  Platform.OS === 'ios'
    ? '<ios-interstitial-ad-unit-id>'
    : '<android-interstitial-ad-unit-id>';
const MAX_EXPONENTIAL_RETRY_COUNT = 6;
let retryAttempt = 0;

// Call once, after Metica.initialize() has resolved.
export function initializeInterstitialAds(): void {
  InterstitialAd.addAdLoadedEventListener((adInfo) => {
    // Ready to show: InterstitialAd.isAdReady() now resolves true
    retryAttempt = 0;
    console.log(`Interstitial loaded from ${adInfo.networkName}`);
  });
  InterstitialAd.addAdLoadFailedEventListener((errorInfo) => {
    // Retry with exponentially higher delays, up to 64 seconds
    retryAttempt += 1;
    const delaySeconds = Math.pow(
      2,
      Math.min(MAX_EXPONENTIAL_RETRY_COUNT, retryAttempt)
    );
    console.log(
      `Interstitial failed to load (${errorInfo.code}: ${errorInfo.message}), retrying in ${delaySeconds}s`
    );
    setTimeout(loadInterstitial, delaySeconds * 1000);
  });
  InterstitialAd.addAdDisplayedEventListener((adInfo) => {
    console.log(`Interstitial shown: ${adInfo.adUnitId}`);
  });
  InterstitialAd.addAdFailedToDisplayEventListener((errorInfo) => {
    console.log(`Interstitial failed to display: ${errorInfo.message}`);
    loadInterstitial();
  });
  InterstitialAd.addAdClickedEventListener(() => {
    console.log('Interstitial clicked');
  });
  InterstitialAd.addAdHiddenEventListener(() => {
    // Preload the next ad
    loadInterstitial();
  });
  InterstitialAd.addAdRevenuePaidListener((adInfo) => {
    console.log(`Interstitial revenue: ${adInfo.revenue} from ${adInfo.networkName}`);
  });

  loadInterstitial();
}

function loadInterstitial(): void {
  InterstitialAd.loadAd(INTERSTITIAL_AD_UNIT_ID);
}

export async function showInterstitial(): Promise<void> {
  if (await InterstitialAd.isAdReady(INTERSTITIAL_AD_UNIT_ID)) {
    // placement and customData are optional, for your reporting
    InterstitialAd.showAd(INTERSTITIAL_AD_UNIT_ID, 'main_menu', 'level_complete');
  } else {
    console.log('Interstitial not ready yet');
  }
}
```

{% endcode %}

To stop listening, for example when a screen that registered the listeners unmounts, remove them:

```typescript
InterstitialAd.removeAdLoadedEventListener();
InterstitialAd.removeAdLoadFailedEventListener();
// ... and the same for the other events you registered
```

### Rewarded Ads

Ads that reward users for watching them. `RewardedAd` has every member of `InterstitialAd`, plus the reward listener.

{% code title="rewarded.ts" %}

```typescript
import { Platform } from 'react-native';
import { RewardedAd } from '@metica/react-native-sdk';

const REWARDED_AD_UNIT_ID =
  Platform.OS === 'ios'
    ? '<ios-rewarded-ad-unit-id>'
    : '<android-rewarded-ad-unit-id>';
const MAX_EXPONENTIAL_RETRY_COUNT = 6;
let retryAttempt = 0;

// Call once, after Metica.initialize() has resolved.
export function initializeRewardedAds(): void {
  RewardedAd.addAdLoadedEventListener(() => {
    retryAttempt = 0;
  });
  RewardedAd.addAdLoadFailedEventListener((errorInfo) => {
    retryAttempt += 1;
    const delaySeconds = Math.pow(
      2,
      Math.min(MAX_EXPONENTIAL_RETRY_COUNT, retryAttempt)
    );
    console.log(
      `Rewarded ad failed to load (${errorInfo.message}), retrying in ${delaySeconds}s`
    );
    setTimeout(loadRewardedAd, delaySeconds * 1000);
  });
  RewardedAd.addAdDisplayedEventListener(() => {
    console.log('Rewarded ad shown');
  });
  RewardedAd.addAdFailedToDisplayEventListener((errorInfo) => {
    console.log(`Rewarded ad failed to display: ${errorInfo.message}`);
    loadRewardedAd();
  });
  RewardedAd.addAdClickedEventListener(() => {
    console.log('Rewarded ad clicked');
  });
  RewardedAd.addAdHiddenEventListener(() => {
    // Preload the next ad
    loadRewardedAd();
  });
  RewardedAd.addAdReceivedRewardEventListener((rewardInfo) => {
    // Grant the reward you configured for this placement
    console.log(`User earned a reward from ${rewardInfo.networkName}`);
  });
  RewardedAd.addAdRevenuePaidListener((adInfo) => {
    console.log(`Rewarded ad revenue: ${adInfo.revenue} from ${adInfo.networkName}`);
  });

  loadRewardedAd();
}

function loadRewardedAd(): void {
  RewardedAd.loadAd(REWARDED_AD_UNIT_ID);
}

export async function showRewardedAd(): Promise<void> {
  if (await RewardedAd.isAdReady(REWARDED_AD_UNIT_ID)) {
    RewardedAd.showAd(REWARDED_AD_UNIT_ID, 'shop', 'extra_coins');
  } else {
    console.log('Rewarded ad not ready yet');
  }
}
```

{% endcode %}

{% hint style="warning" %}
The native Metica SDKs don't report the reward itself: `AdRewardInfo.rewardLabel` is always `null` and `rewardAmount` is always `0`. Grant the reward amount from your own configuration when the reward listener fires.
{% endhint %}

### Ad unit settings

`InterstitialAd` and `RewardedAd` share these settings. You can call them before `Metica.initialize`; the SDK holds the values and applies them when the native SDK starts.

```typescript
// Extra parameters for one ad unit, as in MAX
InterstitialAd.setExtraParameter(INTERSTITIAL_AD_UNIT_ID, 'key', 'value');
InterstitialAd.setLocalExtraParameter(INTERSTITIAL_AD_UNIT_ID, 'key', { nested: true });
```

`loadAd` also takes Metica-only settings for one load. Like any load, call it after `Metica.initialize` has resolved:

```typescript
// Metica-only: your own bid floor (USD CPM) for one load; see the note below
InterstitialAd.loadAd(INTERSTITIAL_AD_UNIT_ID, { overrideBidFloor: 1.5 });
```

{% hint style="info" %}
**Bid floors are Metica's job.** For users in the trial group, Metica puts the floor from its strategy on every MAX load request itself; you don't pass anything for that. `adInfo.overrideBidFloor` reports the floor that was set.

`overrideBidFloor` on a load is your own floor for that one request (USD CPM). With the current native SDKs it has a limited effect: Android doesn't apply it, and iOS applies it only when the load creates the ad unit's MAX ad, in practice a holdout user's first load of that ad unit. A non-finite value is ignored.
{% endhint %}

## Ad Info and Revenue

Every ad listener receives an `AdInfo` (`AdLoadFailedInfo` for load failures, `AdDisplayFailedInfo` for display failures, `AdRewardInfo` for rewards). Use the revenue listener to forward impression revenue to your analytics:

{% code title="revenue.ts" %}

```typescript
import { InterstitialAd, RewardedAd, type AdInfo } from '@metica/react-native-sdk';

function onAdRevenuePaid(adInfo: AdInfo): void {
  const revenue = adInfo.revenue ?? 0; // USD; null when nothing was reported
  const networkName = adInfo.networkName ?? 'unknown';

  console.log(`Ad revenue: ${revenue.toFixed(4)} USD`);
  console.log(`Network: ${networkName}`);
  console.log(`Format: ${adInfo.adFormat}`); // 'INTER' or 'REWARDED'
  console.log(`Placement: ${adInfo.placement}`);

  // Send to your analytics here
}

InterstitialAd.addAdRevenuePaidListener(onAdRevenuePaid);
RewardedAd.addAdRevenuePaidListener(onAdRevenuePaid);
```

{% endcode %}

### AdInfo fields

| Field              | Type                         | Description                                                                                                              |
| ------------------ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `adUnitId`         | `string \| null`             | The ad unit that served the ad. See [Ad unit ids in events](#ad-unit-ids-in-events).                                     |
| `adFormat`         | `string`                     | `'INTER'` or `'REWARDED'`.                                                                                               |
| `networkName`      | `string \| null`             | The ad network that served the ad.                                                                                       |
| `networkPlacement` | `string \| null`             | The network's placement id.                                                                                              |
| `placement`        | `string \| null`             | The placement passed to `showAd`.                                                                                        |
| `creativeId`       | `string \| null`             | The creative id.                                                                                                         |
| `revenue`          | `number \| null`             | Impression revenue in USD.                                                                                               |
| `revenuePrecision` | `string \| null`             | The precision of `revenue`, as reported by MAX.                                                                          |
| `latencyMillis`    | `number \| null`             | Load latency in milliseconds.                                                                                            |
| `waterfall`        | `AdWaterfallInfo` (optional) | The waterfall that served the ad, with one `AdNetworkResponseInfo` per network.                                          |
| `dspName`          | `string \| null`             | Always `null`: not reported by the native Metica SDKs.                                                                   |
| `size`             | `{ width, height }`          | Always `0 x 0`, as for MAX's fullscreen ads.                                                                             |
| `overrideBidFloor` | `number \| null`             | **Metica-only.** The bid floor set on this ad's load request (USD CPM), normally Metica's own; `null` when none was set. |

Fields are `null` when the native SDK reported nothing, where MAX would send `""` or `0`.

### Ad unit ids in events

`adUnitId` is the ad unit id the native Metica SDK reports, which is not always the id you passed to `loadAd`:

* **Holdout users:** the ad unit you requested.
* **Trial users:** the ad unit Metica's waterfall served, which can differ from the one you requested.
* `null` where the native SDK reports none, for example a trial user's load failure on Android.

Handle events per **format** (the listener they arrive on), not by comparing `adUnitId` with the id you loaded. See [Troubleshooting](#troubleshooting).

### Expired ads (Metica-only)

When the mediation SDK replaces an expired cached ad with a new one (holdout users), the SDK calls the expired-ad listener with the previous ad and its replacement:

```typescript
InterstitialAd.addExpiredAdReloadedEventListener((expiredAd, newAd) => {
  console.log(`Ad from ${expiredAd.networkName} expired, reloaded from ${newAd.networkName}`);
});
```

## Analytics (Metica-only) <a href="#analytics-metica-only" id="analytics-metica-only"></a>

`Analytics` sends Metica's analytics events. The methods are named after the Metica Unity SDK. They are fire and forget: the native SDK queues and sends the events.

```typescript
import { Analytics } from '@metica/react-native-sdk';

Analytics.logPurchaseEvent('com.game.gems_100', 'USD', 4.99, 'completed', null, 'txnAbc123', {
  source: 'shop',
});
Analytics.logSessionStartEvent({ entryPoint: 'notification' });
Analytics.logInstallEvent();
Analytics.logImpressionEvent(0.00555, 'Rewarded', 'AppLovin', 'ironSource', 'LevelSuccess');
Analytics.logFullStateUpdateEvent({ playerLevel: 25, totalCoins: 15000 });
Analytics.logPartialStateUpdateEvent({ totalCoins: 16500 });
Analytics.logCustomEvent('levelEnd', { levelIndex: 42, stars: 3 });
```

| Method                                                                                            | Description                                                                                                                                                                                                                               |
| ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `logPurchaseEvent(productId, currency, amount, status, errorCode?, referenceId?, customPayload?)` | An in-app purchase. `currency` is an ISO 4217 code, `amount` the total in that currency, `status` for example `'completed'`, `errorCode` the store's error code for a failed purchase, `referenceId` the store's transaction or order id. |
| `logSessionStartEvent(customPayload?)`                                                            | A session start.                                                                                                                                                                                                                          |
| `logInstallEvent(customPayload?)`                                                                 | An install.                                                                                                                                                                                                                               |
| `logImpressionEvent(value, type, mediator, source, placement?, customPayload?)`                   | An ad impression your app reports itself, for example from another mediator: `value` in USD, `type` the ad format, `mediator` the mediation platform, `source` the network that served it.                                                |
| `logFullStateUpdateEvent(attributes)`                                                             | Replaces the user's state attributes.                                                                                                                                                                                                     |
| `logPartialStateUpdateEvent(attributes)`                                                          | Updates only the given state attributes.                                                                                                                                                                                                  |
| `logCustomEvent(eventName, properties?)`                                                          | A custom event.                                                                                                                                                                                                                           |

Payloads (`AnalyticsPayload`) are flat objects. Values are strings, numbers, booleans, `null`, or arrays of strings, numbers or booleans (one type per array). The native SDK drops a payload with more than 100 keys (or an array with more than 100 items) and truncates strings at 200 characters.

{% hint style="info" %}
Analytics events need `Metica.initialize` or `Metica.initializeAnalytics` to have completed. Events sent before that are dropped, and the native SDK logs why.
{% endhint %}

## Privacy and Consent <a href="#privacy-and-consent" id="privacy-and-consent"></a>

### Privacy settings

Set the user's privacy choices **before** `Metica.initialize`:

```typescript
import { Privacy } from '@metica/react-native-sdk';

// GDPR: the user's consent for personalized ads
Privacy.setHasUserConsent(true);

// CCPA: "Do Not Sell" my data
Privacy.setDoNotSell(false);
```

The setters write AppLovin's privacy settings, which the native Metica SDK also reads for its own events. The getters (`hasUserConsent()`, `isDoNotSell()`, and the Metica-only `isUserConsentSet()`) read them back, before initialization too.

### Terms and privacy policy flow <a href="#terms-and-privacy-policy-flow" id="terms-and-privacy-policy-flow"></a>

The SDK can run AppLovin's terms and privacy policy flow (CMP) during initialization, as `react-native-applovin-max` does. Configure it before `Metica.initialize`; `initialize` then resolves after the flow:

```typescript
import Metica, { ConsentFlowUserGeography } from '@metica/react-native-sdk';

export async function initializeWithConsentFlow(): Promise<void> {
  Metica.setTermsAndPrivacyPolicyFlowEnabled(true);
  Metica.setPrivacyPolicyUrl('https://your-company.com/privacy/');
  Metica.setTermsOfServiceUrl('https://your-company.com/terms/'); // Optional
  if (__DEV__) {
    // Test the GDPR flow from anywhere
    Metica.setConsentFlowDebugUserGeography(ConsentFlowUserGeography.GDPR);
  }

  const configuration = await Metica.initialize({
    apiKey: '<metica-api-key>',
    appId: '<metica-app-id>',
    maxSdkKey: '<applovin-max-sdk-key>',
  });
  if (configuration.cmpFlowError) {
    console.log(`Consent flow error: ${configuration.cmpFlowError}`);
  }
}
```

{% hint style="warning" %}
When the flow is enabled, it needs:

* A Google-certified CMP, such as Google UMP, configured in the AppLovin MAX dashboard for your SDK key. Without one, AppLovin's iOS SDK can crash.

* `NSUserTrackingUsageDescription` in your iOS `Info.plist`. Without it, the flow doesn't show the App Tracking Transparency prompt.

* A privacy policy URL (http or https), set with `Metica.setPrivacyPolicyUrl`. Without one, the SDK doesn't start the flow and `cmpFlowError` says why.
  {% endhint %}

* If the flow doesn't report that it finished within 5 seconds after initialization, `initialize` resolves anyway and `cmpFlowError` says so.

* `Metica.setShowTermsAndPrivacyPolicyAlertInGdpr(show)` is a Metica-only setting for the same flow: whether users in GDPR regions also see AppLovin's terms and privacy policy alert before the consent prompt. Requires AppLovin SDK 13.1.0 or later. On Android the package brings 13.0.1 unless your app or the MAX plugin brings a newer version. With an older version the setting is ignored with a warning, and only the alert before the consent prompt is skipped.

* These setters, like `Metica.setUserId`, only take effect before `initialize`. Later calls log a warning and are ignored.

* Set up Google's User Messaging Platform (UMP) as AppLovin's terms and privacy policy flow documentation describes for MAX.

* AppLovin's native settings files (`applovin_settings.json` on Android, `AppLovin-Settings.plist` on iOS) still work, because the native AppLovin SDK reads them. Configure the flow either there or with the setters, not both.

### Showing the consent form again

After initialization, an existing user can review their choices:

```typescript
const error = await Metica.showCmpForExistingUser();
if (error) {
  console.log(`Could not show the consent form: ${error.message}`);
}
```

`showCmpForExistingUser` resolves `null` on success, or a `CMPError`. The native SDKs report only a message, so `CMPError.code` is `CMPErrorCode.UNSPECIFIED`. `Metica.hasSupportedCmp()` tells you whether a supported CMP is integrated. Both reject when called before `initialize`.

### Consent queries (Metica-only)

| Method                                                  | Returns                                                                                       |
| ------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `Metica.getConsentFlowUserGeography()`                  | `Promise<ConsentFlowUserGeography>`: `GDPR`, `OTHER` or `UNKNOWN` (before initialization).    |
| `Metica.getCountryCode()`                               | `Promise<string>`: the two-letter country code AppLovin resolved, `''` before initialization. |
| `Metica.getTcfVendorConsentStatus(vendorId)`            | `Promise<boolean \| null>`: TCF vendor consent, `null` when unknown.                          |
| `Metica.getAdditionalConsentStatus(atpId)`              | `Promise<boolean \| null>`: Google Additional Consent, `null` when unknown.                   |
| `Metica.getPurposeConsentStatus(purposeId)`             | `Promise<boolean \| null>`: TCF purpose consent, `null` when unknown.                         |
| `Metica.getSpecialFeatureOptInStatus(specialFeatureId)` | `Promise<boolean \| null>`: TCF special feature opt-in, `null` when unknown.                  |

## Using react-native-applovin-max alongside <a href="#using-react-native-applovin-max-alongside" id="using-react-native-applovin-max-alongside"></a>

Metica doesn't cover banners and MRECs in this release, nor app open and native ads. Your app can take those formats from `react-native-applovin-max`, installed next to `@metica/react-native-sdk`:

{% stepper %}
{% step %}

### Initialize Metica first

Call `Metica.initialize`, then `AppLovinMAX.initialize`. Both start the same AppLovin SDK, which keeps the first configuration it receives (Metica's) and logs that it ignores the second.

If the MAX plugin initializes first, AppLovin keeps the plugin's configuration instead. Metica's ads still load, but the user id and the terms and privacy policy flow settings you gave Metica never reach AppLovin, so the terms flow doesn't show. `cmpFlowError` is `null` in that case even though no flow ran.

```typescript
import Metica from '@metica/react-native-sdk';
import AppLovinMAX, { AdViewPosition, BannerAd } from 'react-native-applovin-max';

const BANNER_AD_UNIT_ID = '<banner-ad-unit-id>';

export async function initializeAds(): Promise<void> {
  // 1. Metica: it initializes the AppLovin SDK
  await Metica.initialize({
    apiKey: '<metica-api-key>',
    appId: '<metica-app-id>',
    maxSdkKey: '<applovin-max-sdk-key>',
  });

  // 2. The MAX plugin, for the formats Metica doesn't cover
  await AppLovinMAX.initialize('<applovin-max-sdk-key>');

  BannerAd.createAd(BANNER_AD_UNIT_ID, AdViewPosition.BOTTOM_CENTER);
  BannerAd.showAd(BANNER_AD_UNIT_ID);
}
```

{% endstep %}

{% step %}

### Keep interstitial and rewarded ads on Metica

Load and show interstitial and rewarded ads only through `@metica/react-native-sdk`, and report their revenue from Metica's listeners. Both packages export `InterstitialAd`, `RewardedAd`, `ErrorCode` and other MAX names, so import each name from the package you use it with.
{% endstep %}

{% step %}

### Know what is shared

* **Privacy settings** are shared: AppLovin's privacy settings are process-wide.
* **AppLovin version:** each `react-native-applovin-max` release pins one AppLovin SDK version (9.6.0 pins 13.6.3), which then applies to Metica too. On iOS, run `pod update AppLovinSDK` if your `Podfile.lock` holds another version.
* **Init-only MAX settings** (test device ids, segments, initialization ad unit ids) are ignored, because AppLovin keeps Metica's configuration. For test ads, see [Test ads on real devices](#test-ads-on-real-devices).
* Banners and MRECs shown this way are **plain MAX ads**: Metica doesn't optimize or report them.
  {% endstep %}
  {% endstepper %}

## Debug Logging

`Metica.setVerboseLogging` turns Metica's logs on or off. Called before `initialize`, it also sets AppLovin's verbose logging, because Metica passes the setting on when it initializes AppLovin. Called afterwards, it affects Metica's logs only.

```typescript
Metica.setVerboseLogging(true);
```

On Android you can also enable Metica's logs with ADB:

```bash
adb shell setprop debug.metica.internal_logging true
```

Look for the `Metica` tag in Logcat (the React Native layer logs under `MeticaRN`), or in the Xcode console on iOS. After initialization, `Metica.showMediationDebugger()` opens AppLovin's mediation debugger, and `Metica.getNativeSdkVersion()` and `Metica.VERSION` give the native SDK's and this package's versions.

## Best Practices

{% stepper %}
{% step %}

### Initialize early, once

Call `Metica.initialize()` as early as possible, for example when your app starts. Repeated calls return the same promise, so you can await it wherever you need it.
{% endstep %}

{% step %}

### Set privacy and init-only settings first

Call `Privacy.setHasUserConsent`, `Privacy.setDoNotSell`, `Metica.setUserId` and the terms-flow setters before `initialize`:

```typescript
Privacy.setHasUserConsent(hasConsent);
Privacy.setDoNotSell(doNotSell);
await Metica.initialize({ apiKey, appId, maxSdkKey });
```

{% endstep %}

{% step %}

### Register listeners once

Register each format's listeners once. Adding a listener again replaces the previous one, so you never get duplicate callbacks, but a component that registers listeners should remove them when it unmounts.
{% endstep %}

{% step %}

### Preload ads

Load the next ad as soon as the previous one is hidden:

```typescript
InterstitialAd.addAdHiddenEventListener(() => {
  InterstitialAd.loadAd(INTERSTITIAL_AD_UNIT_ID);
});
```

{% endstep %}

{% step %}

### Check readiness before showing

```typescript
if (await InterstitialAd.isAdReady(INTERSTITIAL_AD_UNIT_ID)) {
  InterstitialAd.showAd(INTERSTITIAL_AD_UNIT_ID);
}
```

{% endstep %}

{% step %}

### Retry with backoff

Use exponential backoff for failed loads to avoid overwhelming the network:

```typescript
const delaySeconds = Math.pow(2, Math.min(6, retryAttempt));
```

{% endstep %}

{% step %}

### Route events by format

Decide what to do from the listener an event arrives on, not from `adInfo.adUnitId`. See [Ad unit ids in events](#ad-unit-ids-in-events).
{% endstep %}
{% endstepper %}

## Migrating from react-native-applovin-max <a href="#migrating-from-react-native-applovin-max" id="migrating-from-react-native-applovin-max"></a>

`@metica/react-native-sdk` keeps the API of `react-native-applovin-max` 9.6.0, so most apps change only a few lines:

1. **Swap the dependency.** Add `@metica/react-native-sdk`. Remove `react-native-applovin-max`, or keep it for banners, MRECs, app open and native ads ([alongside](#using-react-native-applovin-max-alongside)).
2. **Change the imports.** The named exports keep MAX's names (`InterstitialAd`, `RewardedAd`, `Privacy`, `ErrorCode`, the `AdInfo` types). The default export is `Metica` where MAX's is `AppLovinMAX`:

   ```diff
   -import AppLovinMAX, { InterstitialAd, RewardedAd } from 'react-native-applovin-max';
   +import Metica, { InterstitialAd, RewardedAd } from '@metica/react-native-sdk';
   ```
3. **Change `initialize`.** Pass your Metica credentials along with the MAX SDK key:

   ```diff
   -const configuration = await AppLovinMAX.initialize(sdkKey);
   +const configuration = await Metica.initialize({ apiKey, appId, maxSdkKey: sdkKey });
   ```
4. **Move init-only setters before `initialize`.** `setUserId` works only before `initialize` (or pass `userId` in the config).
5. **Route events by format**, accept `null` fields and ad unit ids, and grant rewards from your own configuration.

Before you release, check that:

* `@metica/react-native-sdk` is added, `react-native-applovin-max` is removed or kept only for banners, MRECs, app open and native ads, and pods are installed.
* Your app meets the [requirements](#requirements), which are higher than `react-native-applovin-max`'s.
* The imports are switched and `AppLovinMAX` is renamed to `Metica`.
* `initialize` passes `apiKey`, `appId` and `maxSdkKey`, and `setUserId` and the terms-flow setters run before it.
* Ad listeners route by format, not by `adInfo.adUnitId`, and accept `null` fields.
* Reward amounts come from your own configuration.
* Nothing listed as not available under [Known differences](#known-differences-from-react-native-applovin-max) is still called on `Metica`.

## API Reference

Every name matches `react-native-applovin-max` unless marked **Metica-only**.

### Metica

`Metica` is the default export (MAX: `AppLovinMAX`).

#### Initialization and settings

| Method                                                       | Return Type              | Description                                                                                                                                                                                                              |
| ------------------------------------------------------------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `initialize(config: InitializationConfig)`                   | `Promise<Configuration>` | Initializes Metica, which initializes AppLovin MAX. Later calls return the same promise. Rejects when a key is blank.                                                                                                    |
| `initializeAnalytics(config: AnalyticsInitializationConfig)` | `Promise<void>`          | **Metica-only.** Initializes analytics without ads.                                                                                                                                                                      |
| `isInitialized()`                                            | `Promise<boolean>`       | Whether `initialize` completed and AppLovin initialized successfully.                                                                                                                                                    |
| `setUserId(userId: string)`                                  | `void`                   | Sets the user id. Before `initialize` only.                                                                                                                                                                              |
| `setMuted(muted: boolean)`                                   | `void`                   | Mutes ads. Any time; a value set before initialization is applied when the native SDK starts.                                                                                                                            |
| `isMuted()`                                                  | `Promise<boolean>`       | Whether ads are muted.                                                                                                                                                                                                   |
| `setExtraParameter(key: string, value: string \| null)`      | `void`                   | Sets an SDK-wide extra parameter. Any time.                                                                                                                                                                              |
| `setVerboseLogging(verboseLoggingEnabled: boolean)`          | `void`                   | Turns Metica's logs on or off. Called before `initialize`, it also sets AppLovin's verbose logging, because Metica passes the setting on when it initializes AppLovin. Called afterwards, it affects Metica's logs only. |
| `showMediationDebugger()`                                    | `void`                   | Shows AppLovin's mediation debugger. After initialization.                                                                                                                                                               |
| `isTablet()`                                                 | `Promise<boolean>`       | Whether the device is a tablet.                                                                                                                                                                                          |
| `getNativeSdkVersion()`                                      | `Promise<string>`        | **Metica-only.** The native Metica SDK's version.                                                                                                                                                                        |
| `VERSION`                                                    | `string`                 | **Metica-only.** This package's version.                                                                                                                                                                                 |

#### Consent and the CMP

| Method                                                                      | Return Type                         | Description                                                                                                                                                    |
| --------------------------------------------------------------------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `setTermsAndPrivacyPolicyFlowEnabled(enabled: boolean)`                     | `void`                              | Enables the terms and privacy policy flow. Before `initialize`.                                                                                                |
| `setPrivacyPolicyUrl(urlString: string)`                                    | `void`                              | The privacy policy URL the flow shows (required for the flow). Before `initialize`.                                                                            |
| `setTermsOfServiceUrl(urlString: string)`                                   | `void`                              | The terms of service URL the flow shows. Before `initialize`.                                                                                                  |
| `setConsentFlowDebugUserGeography(userGeography: ConsentFlowUserGeography)` | `void`                              | Overrides the user's geography for testing the flow. Before `initialize`.                                                                                      |
| `setShowTermsAndPrivacyPolicyAlertInGdpr(show: boolean)`                    | `void`                              | **Metica-only.** Whether users in GDPR regions also see AppLovin's terms and privacy policy alert. Requires AppLovin SDK 13.1.0 or later. Before `initialize`. |
| `showCmpForExistingUser()`                                                  | `Promise<CMPError \| null>`         | Shows the consent form again. Rejects before initialization.                                                                                                   |
| `hasSupportedCmp()`                                                         | `Promise<boolean>`                  | Whether a supported CMP is integrated. Rejects before initialization.                                                                                          |
| `getConsentFlowUserGeography()`                                             | `Promise<ConsentFlowUserGeography>` | **Metica-only.**                                                                                                                                               |
| `getCountryCode()`                                                          | `Promise<string>`                   | **Metica-only.**                                                                                                                                               |
| `getTcfVendorConsentStatus(vendorId: number)`                               | `Promise<boolean \| null>`          | **Metica-only.**                                                                                                                                               |
| `getAdditionalConsentStatus(atpId: number)`                                 | `Promise<boolean \| null>`          | **Metica-only.**                                                                                                                                               |
| `getPurposeConsentStatus(purposeId: number)`                                | `Promise<boolean \| null>`          | **Metica-only.**                                                                                                                                               |
| `getSpecialFeatureOptInStatus(specialFeatureId: number)`                    | `Promise<boolean \| null>`          | **Metica-only.**                                                                                                                                               |

#### AppLovin passthroughs

| Method                                                                                  | Return Type | Description                                                                                  |
| --------------------------------------------------------------------------------------- | ----------- | -------------------------------------------------------------------------------------------- |
| `trackEvent(name: string, parameters?: { [key: string]: string })`                      | `void`      | **Metica-only.** AppLovin's event tracking. After initialization.                            |
| `addAdReviewCreativeIdListener(listener: (creativeId: string, adInfo: AdInfo) => void)` | `void`      | **Metica-only.** AppLovin Ad Review creative ids, as they are generated (real devices only). |
| `removeAdReviewCreativeIdListener()`                                                    | `void`      | **Metica-only.**                                                                             |

### Privacy

| Method                                       | Return Type        | Description                                                                     |
| -------------------------------------------- | ------------------ | ------------------------------------------------------------------------------- |
| `setHasUserConsent(hasUserConsent: boolean)` | `void`             | GDPR consent. Before `initialize`.                                              |
| `hasUserConsent()`                           | `Promise<boolean>` |                                                                                 |
| `isUserConsentSet()`                         | `Promise<boolean>` | **Metica-only.** Whether consent was set at all, in this or an earlier session. |
| `setDoNotSell(doNotSell: boolean)`           | `void`             | CCPA "Do Not Sell". Before `initialize`.                                        |
| `isDoNotSell()`                              | `Promise<boolean>` |                                                                                 |

### InterstitialAd and RewardedAd

#### Methods

| Method                                                                                   | Return Type        | Description                                                    |
| ---------------------------------------------------------------------------------------- | ------------------ | -------------------------------------------------------------- |
| `loadAd(adUnitId: string, config?: AdLoadConfig)`                                        | `void`             | Loads an ad. `config.overrideBidFloor` is **Metica-only**.     |
| `showAd(adUnitId: string, placement?: string \| null, customData?: string \| null)`      | `void`             | Shows an ad.                                                   |
| `isAdReady(adUnitId: string)`                                                            | `Promise<boolean>` | Whether an ad is ready to show; `false` before initialization. |
| `setExtraParameter(adUnitId: string, key: string, value: string \| null)`                | `void`             | Sets an extra parameter for an ad unit. Any time.              |
| `setLocalExtraParameter(adUnitId: string, key: string, value: LocalExtraParameterValue)` | `void`             | Sets a local extra parameter for an ad unit. Any time.         |

#### Listeners

Each `add…` method has a matching `remove…()` that takes no argument.

| Listener                                               | Payload                              | Description                                         |
| ------------------------------------------------------ | ------------------------------------ | --------------------------------------------------- |
| `addAdLoadedEventListener`                             | `AdInfo`                             | An ad loaded.                                       |
| `addAdLoadFailedEventListener`                         | `AdLoadFailedInfo`                   | An ad failed to load.                               |
| `addAdDisplayedEventListener`                          | `AdInfo`                             | An ad was shown.                                    |
| `addAdFailedToDisplayEventListener`                    | `AdDisplayFailedInfo`                | An ad failed to show.                               |
| `addAdClickedEventListener`                            | `AdInfo`                             | An ad was clicked.                                  |
| `addAdHiddenEventListener`                             | `AdInfo`                             | An ad was dismissed.                                |
| `addAdRevenuePaidListener`                             | `AdInfo`                             | Revenue was recorded for an impression.             |
| `addAdReceivedRewardEventListener` (`RewardedAd` only) | `AdRewardInfo`                       | The user earned the reward.                         |
| `addExpiredAdReloadedEventListener`                    | `(expiredAd: AdInfo, newAd: AdInfo)` | **Metica-only.** An expired cached ad was replaced. |

### Analytics

**Metica-only.** See [Analytics](#analytics-metica-only) for the methods.

### Types

| Type                                                              | Fields                                                                                                                                                     |
| ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `InitializationConfig`                                            | **Metica-only.** `apiKey`, `appId`, `maxSdkKey`, `userId?`                                                                                                 |
| `AnalyticsInitializationConfig`                                   | **Metica-only.** `apiKey`, `appId`, `userId?`                                                                                                              |
| `Configuration`                                                   | `countryCode`, `consentFlowUserGeography`, and the **Metica-only** `userGroup`, `isForcedHoldout`, `isSuccess`, `userId`, `cmpFlowError?`                  |
| `AdInfo`                                                          | See [AdInfo fields](#adinfo-fields).                                                                                                                       |
| `AdLoadFailedInfo`                                                | `adUnitId`, `code`, `message`, `mediatedNetworkErrorCode`, `mediatedNetworkErrorMessage`, `waterfall?`, and the **Metica-only** `latencyMillis`            |
| `AdDisplayFailedInfo`                                             | `AdInfo` plus `code`, `message`, `mediatedNetworkErrorCode`, `mediatedNetworkErrorMessage`                                                                 |
| `AdRewardInfo`                                                    | `AdInfo` plus `rewardLabel` (always `null`) and `rewardAmount` (a `number`, always `0`)                                                                    |
| `AdWaterfallInfo`                                                 | `name`, `testName`, `networkResponses`, `latencyMillis`                                                                                                    |
| `AdNetworkResponseInfo`                                           | `adLoadState`, `mediatedNetwork?`, `credentials` (always empty), `error?`, `latencyMillis`, and the **Metica-only** `isBidding` and `initializationStatus` |
| `AdMediatedNetworkInfo`                                           | `name`, `adapterClassName`, `adapterVersion`, `sdkVersion`                                                                                                 |
| `AdErrorInfo`                                                     | `code`, `message?`                                                                                                                                         |
| `CMPError`                                                        | `code`, `message`, `cmpCode` and `cmpMessage` (both always `null`)                                                                                         |
| `AdEventListener<T>`                                              | `(event: T) => void`: the type of the ad listeners                                                                                                         |
| `LocalExtraParameterValue`                                        | Any JSON value: a string, number, boolean, `null`, or an object or array of these                                                                          |
| `AdLoadConfig`                                                    | **Metica-only.** `overrideBidFloor?` (USD CPM)                                                                                                             |
| `MeticaUserGroup`                                                 | **Metica-only.** `'TRIAL' \| 'HOLDOUT'`                                                                                                                    |
| `AnalyticsPayload`                                                | **Metica-only.** `{ [key: string]: AnalyticsValue }`                                                                                                       |
| `AnalyticsValue`                                                  | **Metica-only.** `string`, `number`, `boolean`, `null`, `string[]`, `number[]` or `boolean[]`                                                              |
| `MeticaType`, `PrivacyType`, `FullscreenAdType`, `RewardedAdType` | The types of `Metica` (MAX: `AppLovinMAXType`), `Privacy`, `InterstitialAd` and `RewardedAd`                                                               |
| `AnalyticsType`                                                   | **Metica-only.** The type of `Analytics`                                                                                                                   |

### Enums

| Enum                       | Values                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ErrorCode`                | MAX's values: `UNSPECIFIED` (-1), `NO_FILL` (204), `AD_LOAD_FAILED` (-5001), `AD_DISPLAY_FAILED` (-4205), `NETWORK_ERROR` (-1000), `NETWORK_TIMEOUT` (-1001), `NO_NETWORK` (-1009), `FULLSCREEN_AD_ALREADY_SHOWING` (-23), `FULLSCREEN_AD_NOT_READY` (-24), `FULLSCREEN_AD_INVALID_VIEW_CONTROLLER` (-25), `DONT_KEEP_ACTIVITIES_ENABLED` (-5602), `INVALID_AD_UNIT_ID` (-5603). A failure's `code` can also be a mediation-specific value outside this list. |
| `ConsentFlowUserGeography` | `UNKNOWN`, `GDPR`, `OTHER`                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `CMPErrorCode`             | `UNSPECIFIED`, `INTEGRATION_ERROR`, `FORM_UNAVAILABLE`, `FORM_NOT_REQUIRED`                                                                                                                                                                                                                                                                                                                                                                                   |
| `AdLoadState`              | `LoadStateAdLoadNotAttempted`, `LoadStateAdLoaded`, `LoadStateAdFailedToLoad`                                                                                                                                                                                                                                                                                                                                                                                 |

## Troubleshooting <a href="#troubleshooting" id="troubleshooting"></a>

### Important considerations while integrating

These are the patterns that most often go wrong. Most of them fail **silently**: no crash, just missing ads, revenue or callbacks.

{% stepper %}
{% step %}

#### Comparing requested and returned ad unit ids

Don't gate listener logic on the ad unit id you requested:

{% hint style="danger" %}

```typescript
// DON'T do this
InterstitialAd.addAdRevenuePaidListener((adInfo) => {
  if (adInfo.adUnitId !== requestedAdUnitId) return; // silently drops revenue
  reportRevenue(adInfo);
});
```

{% endhint %}

For trial users Metica can serve a different ad unit than the one you requested, and `adUnitId` can be `null`. This pattern often comes from MAX integration code, where it is harmless; with Metica it drops events. Route by the listener an event arrives on instead.
{% endstep %}

{% step %}

#### Loading the same format twice at once

For trial users, Metica runs one waterfall per format. A second `loadAd` for the same format while a load is in progress gets no callback of its own. Wait for the loaded or load-failed listener before loading that format again.
{% endstep %}

{% step %}

#### Loading ads before initialization completes

Ad calls made before `Metica.initialize` has completed don't throw: they fail through the load-failed or display-failed listener with the message "`MeticaSdk.Ads` cannot be accessed before initialization". Await `initialize` before your first `loadAd`.
{% endstep %}

{% step %}

#### Setting init-only values after initialization

`setUserId` and the terms-flow setters only take effect before `initialize`. Later calls log a warning (`[Metica] … has no effect after initialize()`) and are ignored.
{% endstep %}

{% step %}

#### Keeping interstitial or rewarded ads on the MAX plugin

If you keep `react-native-applovin-max` installed, ads you load through it bypass Metica. Load interstitial and rewarded ads only through `@metica/react-native-sdk`, and report their revenue from Metica's listeners only.
{% endstep %}

{% step %}

#### Granting the reward from AdRewardInfo

`rewardAmount` is always `0` and `rewardLabel` always `null`. Grant the amount from your own configuration.
{% endstep %}
{% endstepper %}

### Test ads on real devices

To receive test ads on a real device, turn on AppLovin's test mode in the mediation debugger: after initialization, call `Metica.showMediationDebugger()` and enable test ads there. AppLovin's other way to turn on test mode, passing test device advertising ids before initialization, isn't available, because Metica initializes the AppLovin MAX SDK. See AppLovin's [Test Mode](https://support.applovin.com/en/max/react-native/testing-networks/test-mode) documentation.

The mediation debugger also shows which adapters your app includes and how each network is set up for your ad units, which helps when a network doesn't fill.

{% hint style="info" %}
No fills are common during testing and don't necessarily mean that something is wrong with your integration.
{% endhint %}

### Known differences from react-native-applovin-max

* **New Architecture only.** `react-native-applovin-max` also supports the legacy architecture.
* **`initialize`** takes a config object and rejects on a blank key. `Configuration` has no `isTestModeEnabled` or `appTrackingStatus`.
* **`setUserId`** works only before `initialize`.
* **`setVerboseLogging`** turns Metica's logs on or off. Called before `initialize`, it also sets AppLovin's verbose logging, because Metica passes the setting on when it initializes AppLovin. Called afterwards, it affects Metica's logs only.
* **Ad unit ids and nullable fields** in payloads, as described in [Ad Info and Revenue](#ad-info-and-revenue).
* **`AdRewardInfo.rewardAmount`** is a `number` (always `0`), where MAX types it as a `string`.
* **Payload fields left out:** `adLoadFailureInfo` (deprecated in MAX), `adViewId` and `AdInfo.nativeAd`, which belong to formats Metica doesn't cover.
* **Ad calls before `initialize`** report a failure through the listeners, where MAX only logs an error.
* **`showCmpForExistingUser`** errors always have `code: CMPErrorCode.UNSPECIFIED`.
* **Not available**, because Metica has no backing for them: banners and MRECs in this release (`BannerAd`, `MRecAd`, `<AdView>` and preloading), `AppOpenAd`, `NativeAdView` and its asset views, `setTestDeviceAdvertisingIds`, `setCreativeDebuggerEnabled`, `setInitializationAdUnitIds`, `addSegment`, `getSegments` and `AppTrackingStatus`.

### Known issues

* **Android: no Activity when showing.** `showAd` needs the app's current Activity. If there is none (for example before the app's Activity has resumed), the display-failed listener fires with "No Activity is attached to the React context".
* **iOS: AppLovin version conflict with the MAX plugin.** If `pod install` fails on `AppLovinSDK` after you add `react-native-applovin-max`, run `pod update AppLovinSDK`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.metica.com/api/react-native-sdk.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
