# CAS.AI Developer Docs

Increase your mobile app monetization efficiency with CAS.AI.

## Docs

### CAS.AI Android SDK

Source: https://production.docs.page/docs/android

```mdx

Integrating CAS SDK into an app is the first step toward displaying ads and earning revenue. 
Once you've integrated and initialized the SDK, you can choose an ad format and follow the steps to implement it.

## App prerequisites
Make sure that your app's build file uses the following values:
- Minimum SDK version of `{{ min.api }}` or higher
- Compile SDK version of `{{ min.targetapi }}` or higher
- Kotlin version of `{{ min.kotlin }}` or higher

## Add Maven repositories
In your Gradle settings file (`<project>/settings.gradle.kts`), include the
following `repositories` block so that Gradle can download the artifacts of ad networks:

<AccordionGroup>
<Accordion defaultOpen title="Manven Ads repositories">
```kotlin
dependencyResolutionManagement {
  repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
  repositories {
    google()
    mavenCentral()
    maven {
        name = "MintegralAdsRepo"  
        url = uri("https://dl-maven-android.mintegral.com/repository/mbridge_android_sdk_oversea")  
        content { includeGroup("com.mbridge.msdk.oversea") }  
    }  
    maven {
        name = "PangleAdsRepo"  
        url = uri("https://artifact.bytedance.com/repository/pangle")  
        content { includeGroup("com.pangle.global") }  
    }
    maven {
        name = "ChartboostAdsRepo"  
        url = uri("https://cboost.jfrog.io/artifactory/chartboost-ads/")  
        content {
          includeGroup("com.chartboost")
          includeGroup("com.iab.omid.library")
      }
    }
    maven {  
        name = "YSONetworkRepo"  
        url = uri("https://ysonetwork.s3.eu-west-3.amazonaws.com/sdk/android")  
        content { includeGroup("com.ysocorp") }  
    }
    maven {  
        name = "OguryAdsRepo"  
        url = uri("https://maven.ogury.co")  
        content {  
            includeGroup("co.ogury")  
            includeGroup("co.ogury.module")  
        }  
    }  
    maven {  
        name = "SmaatoAdsRepo"  
        url = uri("https://s3.amazonaws.com/smaato-sdk-releases/")  
        content { 
            includeGroup("com.smaato.android.sdk")
            includeGroup("com.verve")
        }  
    }  
    maven {
        name = "VerveAdsRepo"
        url = uri("https://verve.jfrog.io/artifactory/verve-gradle-release")
        content {
            includeGroup("net.pubnative")
            includeGroup("com.verve")
            includeGroup("com.smaato.android.sdk")
        }
    }
    maven {
        name = "SuperAwesomeRepo"
        url = uri("https://aa-sdk.s3-eu-west-1.amazonaws.com/android_repo/")
        content { includeGroup("tv.superawesome.sdk.publisher") }
    }
  }
}
```
</Accordion>
<Accordion title="Maven Ads repositories for Closed beta">

Read more about Closed beta ads partners on [Mediation Networks](android/mediated-networks) page.  
```kotlin
    maven {
        name = "BidMachineAdsRepo"
        url = uri("https://artifactory.bidmachine.io/bidmachine")
        content {
            includeGroup("io.bidmachine")
            includeGroup("io.bidmachine.libs")
            includeGroup("io.bidmachine.media3")
            includeGroup("com.explorestack")
        }
    }
    maven {
        name = "PubmaticAdsRepo"
        url = uri("https://repo.pubmatic.com/artifactory/public-repos")
        content { includeGroup("com.pubmatic.sdk") }
    }
    maven {
        name = "DisplayIOAdsRepo"
        url = uri("https://maven.display.io/")
        content { includeGroup("com.brandio.ads") }
    }
```

</Accordion>
</AccordionGroup>

If your project is using Gradle version below 7.0, the `repositories` block should be added to the `allprojects` block in the root-level `build.gradle` file.

## Integration options
You can integrate CAS to your Android app using one of the following options:
- **Option 1**: Use the CAS Gradle plugin setup workflow _(recommended, below)_.
- **Option 2**: Use the [default Gradle setup](android/manual-setup) _(may require additional configuration)_.

## Add CAS Gradle Plugin
The CAS SDK provide a Gradle Plugin to simplify and automate certain integration steps. 
Our plugin will automatically add mediated network dependencies to your project, which you configure in an `cas { }` block.

In your module **(app-level)** Gradle file (usually `<project>/<app-module>/build.gradle`), add the CAS services plugin inside the `plugins` block.
```groovy
plugins {
    id("com.android.application") // before CAS plugin
    id("com.cleveradssolutions.gradle-plugin") version "{{ versions.android }}"
}

cas {
    // Plugin configuration
}
```

<Card title="Subscribe" icon="github" href="https://github.com/cleveradssolutions/CAS-Android/subscription">
Subscribe to receive notifications about CAS updates.
</Card>

<AccordionGroup>
<Accordion title="What is CAS ID?">

In most cases, a `casId` is the same as your application package name.
- A [package name](https://developer.android.com/studio/build/application-id) uniquely identifies your app on the device and in the Google Play Store.
- The package name value is case-sensitiv and is often referred to as an `APPLICATION_ID`.
- Find your app's package name in your module (app-level) Gradle file, usually `app/build.gradle` (example package name: `com.yourcompany.yourproject`).

</Accordion>
<Accordion title="How integrate CAS plugin in library module?">

To integrating the plugin into the module `id("com.android.library")` (**library-level**) you must define the `cas.casId` property. 
```groovy
plugins {
    id("com.android.library") // before CAS plugin
    id("com.cleveradssolutions.gradle-plugin") version $casVersion
}

cas {
    casId = "com.yourcompany.yourproject"
}
```

</Accordion>
<Accordion title="How override CAS ID for Product Flavors in app module?">

For the application module as a CAS Id will be selected the final `applicationId` with all modifications.
```groovy
android {
    flavorDimensions.add("version")
    productFlavors {  
        create("first") {  
            dimension = "version"  
            applicationIdSuffix = ".fisrt"  
        }  
        create("second") {  
            dimension = "version"  
            applicationIdSuffix = ".second" 
        }  
    }
}
```

`casId` settings will be ignored when integrating into app-level modules, as the `applicationId` (with all modifications for Build Variant and Product Flavor) will always be used as the CAS ID.

Note that you must register each final `applicationId` as a separate CAS ID in platform.

</Accordion>
<Accordion title="How override CAS ID for Product Flavors in library module?">

To integrate a CAS plugin into the `id("com.android.library")` module (**library level**), you must define the `cas.casId` property in the body of each product flavor.
```groovy
cas {
   casId = "com.yourcompany.yourproject"
   addCasIdVariant("second", "com.yourcompany.yourproject.second")
}

android {
    flavorDimensions.add("version")
    productFlavors {  
        create("first") {  
            dimension = "version"  
        }  
        create("second") {  
            dimension = "version"  
        }  
    }
}
```

Note that you cannot use `applicationId` because the library module does not have information about the application.

</Accordion>
</AccordionGroup>

## Choose Mediated Networks
<Warning>
CAS.AI is a mediation SDK with no built-in live ad inventory. At least one ad network adapter or solution must be integrated before publishing to display ads and generate revenue.
</Warning>

Choose an integration path based on your app's target audience. If you're unsure which solution best fits your application, please contact your account manager.

<Info>
During development, you can test ad formats using [Test Ads](android/enabling-test-ads) without adding any ad network SDKs.
</Info>

<AccordionGroup>
<Accordion defaultOpen title="Optimal Ads Solution">

Recommended for **most applications** targeting a **general or mixed audience**. Includes a broad set of stable, high-performance networks. 

```groovy
cas {
    includeOptimalAds = true
}
```

> Networks included: Google Ads, Unity Ads, IronSource, Liftoff Monetize, InMobi, Yango Ads, Mintegral, Pangle, AppLovin, Audience Network, Bigo, CAS Exchange, Monetrix, Moloco, YSO Network.

</Accordion>
<Accordion title="Families Ads Solution">

Required for applications **directed exclusively at children**, in accordance with the [Google Play Families Policy](https://support.google.com/googleplay/android-developer/answer/12918983?hl=en). 

```groovy
cas {
    includeFamiliesAds = true
}
```

> Networks included: Google Ads, Unity Ads, IronSource, Liftoff Monetize, InMobi, Chartboost, Kidoz.

</Accordion>
<Accordion title="VPN Compliant Ads Solutions">

Designed specifically for applications that provide VPN or proxy services. This solution includes partner networks that comply with VPN-related traffic policies and restrictions.

```groovy
cas {
    includeVPNCompliantAds = true
}
```

> Networks included: Google Ads, Unity Ads, IronSource, Liftoff Monetize, InMobi, Mintegral, Bigo Ads, Yango Ads, YSO Network, Monetrix, Bidease, BlueSea.

</Accordion>
<Accordion title="Choice networks">

Advanced publishers who are familiar with ad network integrations can choose their own set of adapters. If you have any questions or need assistance, please contact your account manager.  

Follow the instructions on the [Mediated Networks](android/mediated-networks) page.

</Accordion>
</AccordionGroup>

## Google Advertising Identifier
The [Advertising ID](https://support.google.com/googleplay/android-developer/answer/6048248?hl=en) is a unique, user-resettable, and user-deletable ID for advertising, provided by Google Play services.

```groovy
cas {
    useAdvertisingId = true
}
```

<Info>
An application must not use an advertising identifier if **at least one** of the following conditions is true:
- The app’s target audience includes **only children**, as defined in the [Families Policy](https://support.google.com/googleplay/android-developer/answer/9893335?sjid=10683822576513227860-EU).
- The app is being built for **devices that do not use Google Play Services** (e.g. Amazon or Huawei devices).
</Info>

## Enable Code minification
Enabling `minifyEnabled` is a crucial step in optimizing your mobile application, especially when integrating ad mediation SDKs that augment your codebase's size. By leveraging code minification, you not only reduce the overall footprint of your app but also enhance its performance, security, and compatibility.
```kotlin
android {
    buildTypes {  
        release {  
            isMinifyEnabled = true
            proguardFiles(...)
        }  
    }
    ...
}
```

<Info>
The CAS SDK and adapters come bundled with the required ProGuard rules in the AARs. Therefore, you do not need to add any additional ProGuard rules to your project.
</Info>

## Optional permissions 
The following permissions are not required for our SDK or 3rd-party SDKs to function, but including them in your `AndroidManifest.xml` may result in improved eCPM and user experience.
```xml
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>  
```
```

### CAS.AI plugin for Construct

Source: https://production.docs.page/docs/construct

```mdx

Integrating CAS SDK into an app is the first step toward displaying ads and earning revenue. 
Once you've integrated and initialized the SDK, you can choose an ad format and follow the steps to implement it.

## Install CAS.AI addon

<Steps>
<Step>
Visit [releases assets](https://github.com/cleveradssolutions/CAS-Construct/releases) to get the latest version of the `.c3addon`.
</Step>
<Step>
Navigate to `Menu > View > Addon Manager` window.
</Step>
<Step>
Install new addon...
</Step>
<Step>
Select the `CASMobileAds.c3addon`.
</Step>
</Steps>

<Card title="Subscribe" icon="github" href="https://github.com/cleveradssolutions/CAS-Cordova/subscription">
Subscribe to receive notifications about CAS updates.
</Card>

<Card title="Construct" href="https://www.construct.net/en/make-games/addons/1532/cas-ai-mobile-ads">
The CAS.AI addon is also published on Construct products at the link.
</Card>

## Create CAS.AI Mobile Ads object
Double-click on layout to add a new object. Find `CAS.AI` object and click insert.

<Image width="671" alt="image" src="/assets/construct/createobject.png" />

Select created object to configure CAS.AI plugin.

Some required configuration steps for your project will be performed automatically using the CAS Gradle plugin for Android and the CAS Ruby script for iOS. You need to register your app on the https://cas.ai platform using the bundle package name for Android and the iTunes ID for iOS.
- For Android the bundle package name will be detected automatically.
- **For iOS you must specify the registered iTunes ID** in the `CAS Id (iTunes Id)` plugin properties. If you do not provide your iTunes ID, the ads in your app will be replaced with test ads.

<AccordionGroup>
<Accordion title="What is CAS ID in iOS?">

In most cases, a CASID is the same as your app store ID.  
You can find an app store ID in the URL of your app’s Apple App Store URL. For example, the URL is `apps.apple.com/us/app/id123456789` then app store ID is `123456789`.  
 
</Accordion>
</AccordionGroup>


## Choose Mediated Networks
<Warning>
CAS.AI is a mediation SDK with no built-in live ad inventory. At least one ad network adapter or solution must be integrated before publishing to display ads and generate revenue.
</Warning>

Choose an integration path based on your app's target audience. If you're unsure which solution best fits your application, please contact your account manager.

Check the details of the ad network adapters supported by CAS.AI Mediation in the [Android repository](https://github.com/cleveradssolutions/CAS-Android/blob/master/Adapters/README.md) and [iOS repository](https://github.com/cleveradssolutions/CAS-iOS/blob/master/Adapters/README.md) tables.

<Info>
During development, you can test ad formats using Test Ads mode without adding any ad network SDKs.
</Info>

### Optimal Ads Solution
Recommended for **most applications** targeting a **general or mixed audience**. Includes a broad set of stable, high-performance networks.

- iOS Integration  
  Solutions: `Optimal`
- Android Integration  
  Solutions: `Optimal`

### Families Ads Solution
Required for applications **directed exclusively at children**, in accordance with the [Google Play Families Policy](https://support.google.com/googleplay/android-developer/answer/12918983?hl=en) and fully compatible with the [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy).

- iOS Integration  
  Solutions: `Families`
- Android Integration  
  Solutions: `Families`

### Choice networks
Advanced publishers familiar with ad network integrations can configure their own set of adapters. 
Add the adapter names you want to CAS_ADAPTERS variables from the linked list for each platform, separating them with `,`, `;`, or a space (` `).

<Tabs groupId="platform">
<TabItem label="Android" value="android">
For Android, the name must match the Adapter names from the [Android Adapters table](https://github.com/cleveradssolutions/CAS-Android/blob/master/Adapters/README.md). Below, as an example, only GoogleAds, CASExchange, and DTExchange are shown.

- Android Integration  
  Adapters: `googleAds casExchange dtExchange`


</TabItem>
<TabItem label="iOS" value="ios">
For iOS, the name must match the Adapter names from the [iOS Adapters table](https://github.com/cleveradssolutions/CAS-Android/blob/master/Adapters/README.md). Below, as an example, only GoogleAds, CASExchange, and DTExchange are shown.

- iOS Integration  
  Adapters: `GoogleAds CASExchange DTExchange`


</TabItem>
</Tabs>

## Advertising Identifier
CAS Mediation uses the [Google Advertising ID](https://support.google.com/googleplay/android-developer/answer/6048248?hl=en) and [Apple Identifier for Advertisers (IDFA)](https://developer.apple.com/documentation/adsupport) to deliver personalized and more relevant ads to each user.  
To enable the use of the Advertising ID in your app, you need to complete the following setup steps.

<Tabs groupId="platform">
<TabItem label="Android" value="android">
CAS Mediation allows you to easily enable or disable (`true` or `false`) the use of the Advertising ID, depending on your app’s privacy requirements.

- Android Integration  
  Use Ad ID: `true`


An application must not use an advertising identifier if **at least one** of the following conditions is true:
- The app’s target audience includes **only children**, as defined in the [Families Policy](https://support.google.com/googleplay/android-developer/answer/9893335?sjid=10683822576513227860-EU).
- The app is being built for **devices that do not use Google Play Services** (e.g. Amazon or Huawei devices).

</TabItem>
<TabItem label="iOS" value="ios">
To use the [App Tracking Transparency authorization request](https://developer.apple.com/documentation/bundleresources/information_property_list/nsusertrackingusagedescription) for accessing the IDFA, add plugin variable `IOS_USER_TRACKING_USAGE` to the `config.xml` with a custom message describing your usage. Below is an example description text:

- iOS Integration  
  Tracking Usage Description: `Your data will remain confidential and will only be used to provide you a better and personalised ad experience`

<AccordionGroup>
<Accordion title="Usage description examples">

- Your data will remain confidential and will only be used to provide you a better and personalised ad experience
- Your data will be used to provide you a better and personalised ad experience
- Your data will be used to create a customized experience tailored to your interests
- Allowing tracking will enable more personalized ads for you
- We try to show ads for apps and products that will be most interesting to you based on the apps you use
- This identifier will be used to deliver personalized ads to you
- This only uses device info for more interesting and relevant ads

</Accordion>
</AccordionGroup>

</TabItem>
</Tabs>

## App information

### Target Audience
Mark apps as child-directed or COPPA-applicable in the CAS UI. If you know specific users are COPPA-applicable, set the audience:

- `Children` - Compliance with all applicable legal regulations and industry standards relating to advertising to children.
- `Not Children` - Audiences over the age of 13 NOT subject to the restrictions of child protection laws.
- `Unknown` - For app's target age groups include both children and older audiences, any ads that may be shown to children must comply with Google Play's Families Ads Program.

### App Keyworkds
Set a list of keywords, interests, or intents related to your application, separated by `,`. Words or phrases describe the current activity of the user for targeting purposes.

### App Conetnt URL
Set the content URL for a website whose content matches the app's primary content. This website content is used for targeting and brand safety purposes. Limitation: max URL length 512.

### Mediation Extras
Additional custom parameters passed to mediation metworks. In JSON format.

#### Meta Audience Network Data Processing Options for US Users
Meta Audience Network Data Processing Options for US Users Limited Data Use is a data processing option that gives you more control over how your data is used in Meta’s systems and better supports your compliance efforts with various US state privacy regulations. To utilize this feature, you must proactively enable Limited Data Use.
Visit [Meta’s developer documentation](https://developers.facebook.com/docs/marketing-apis/data-processing-options) for details.

If you do not want to enable Limited Data Use (LDU) mode, pass an empty string as a value of mediation extras with key `FB_dp`:

- App Information  
  Mediation Extras: `{"FB_dp":""}`
  

To enable LDU for users and specify user geography, set `LDU`:

- App Information  
  Mediation Extras: `{"FB_dp":"LDU"}`
```

### CAS.AI plugin for Cordova

Source: https://production.docs.page/docs/cordova

```mdx

Integrating CAS SDK into an app is the first step toward displaying ads and earning revenue. 
Once you've integrated and initialized the SDK, you can choose an ad format and follow the steps to implement it.

## Prerequisites
Before adding the plugin, you need to modify the `config.xml` of project. 

Make sure that your app's `config.xml` file uses the following minimum values:
```xml
<platform name="ios">
    <preference name="deployment-target" value="{{ min.ios }}" />
</platform>
<platform name="android">
    <preference name="android-targetSdkVersion" value="{{ min.targetapi }}" />
</platform>
```

## CAS Plugin variables
Some required configuration steps for your project will be performed automatically using the CAS Gradle plugin for Android and the CAS Ruby script for iOS. You need to register your app on the https://cas.ai platform using the bundle package name for Android and the iTunes ID for iOS.
- For Android the bundle package name will be detected automatically.
- **For iOS you must specify the registered iTunes ID** in the `IOS_CAS_ID` plugin variable. If you do not provide your iTunes ID, the ads in your app will be replaced with test ads.

All plugin variables must be defined within the `<plugin>` tag, for example `IOS_CAS_ID`.
```xml
<plugin name="cordova-plugin-casai" spec="*">
    <variable name="IOS_CAS_ID" value="123456789" />
    <!-- All plugin variables here -->
</plugin>
```

<AccordionGroup>
<Accordion title="What is CAS ID in iOS?">

In most cases, a CASID is the same as your app store ID.  
You can find an app store ID in the URL of your app’s Apple App Store URL. For example, the URL is `apps.apple.com/us/app/id123456789` then app store ID is `123456789`.  
 
</Accordion>
</AccordionGroup>

## Choose Mediated Networks
<Warning>
CAS.AI is a mediation SDK with no built-in live ad inventory. At least one ad network adapter or solution must be integrated before publishing to display ads and generate revenue.
</Warning>

Choose an integration path based on your app's target audience. If you're unsure which solution best fits your application, please contact your account manager.

<Info>
During development, you can test ad formats using [Test Ads](cordova/enabling-test-ads) without adding any ad network SDKs.
</Info>

Check the details of the ad network adapters supported by CAS.AI Mediation in the [Android repository](https://github.com/cleveradssolutions/CAS-Android/blob/master/Adapters/README.md) and [iOS repository](https://github.com/cleveradssolutions/CAS-iOS/blob/master/Adapters/README.md) tables.

The plugin variables `CAS_SOLUTIONS` and `CAS_ADAPTERS` can include multiple values separated by `,`, `;`, or a space (` `).


<AccordionGroup>
<Accordion defaultOpen title="Optimal Ads Solution">

Recommended for **most applications** targeting a **general or mixed audience**. Includes a broad set of stable, high-performance networks.

```xml
<variable name="IOS_CAS_SOLUTIONS" value="optimal" />
<variable name="ANDROID_CAS_SOLUTIONS" value="optimal" />
```

</Accordion>
<Accordion title="Families Ads Solution">

Required for applications **directed exclusively at children**, in accordance with the [Google Play Families Policy](https://support.google.com/googleplay/android-developer/answer/12918983?hl=en) and fully compatible with the [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy).

```xml
<variable name="IOS_CAS_SOLUTIONS" value="families" />
<variable name="ANDROID_CAS_SOLUTIONS" value="families" />
```

</Accordion>
<Accordion title="VPN Compliant Ads Solutions">

Designed specifically for applications that provide VPN or proxy services. This solution includes partner networks that comply with VPN-related traffic policies and restrictions.

```xml
<variable name="IOS_CAS_SOLUTIONS" value="vpnCompliant" />
<variable name="ANDROID_CAS_SOLUTIONS" value="vpnCompliant" />
```

</Accordion>
<Accordion title="Choice networks">

Advanced publishers familiar with ad network integrations can configure their own set of adapters. 
Add the adapter names you want to `CAS_ADAPTERS` variables from the linked list for each platform.

- For iOS, the name must match the Adapter names (first column) from the [iOS Adapters table](https://github.com/cleveradssolutions/CAS-iOS/blob/master/Adapters/README.md). 
- For Android, the name must match the Adapter names (first column) from the [Android Adapters table](https://github.com/cleveradssolutions/CAS-Android/blob/master/Adapters/README.md). 

Below, as an example, only GoogleAds, CASExchange, and DTExchange are shown.
```xml
<variable name="IOS_CAS_ADAPTERS" value="GoogleAds CASExchange DTExchange" />
<variable name="ANDROID_CAS_ADAPTERS" value="googleAds casExchange dtExchange" />
```

</Accordion>
</AccordionGroup>

## Advertising Identifier
CAS Mediation uses the [Google Advertising ID](https://support.google.com/googleplay/android-developer/answer/6048248?hl=en) and [Apple Identifier for Advertisers (IDFA)](https://developer.apple.com/documentation/adsupport) to deliver personalized and more relevant ads to each user.  
To enable the use of the Advertising ID in your app, you need to complete the following setup steps.

<Tabs groupId="platform">
<TabItem label="Android" value="android">
CAS Mediation allows you to easily enable or disable (`true` or `false`) the use of the Advertising ID, depending on your app’s privacy requirements.

```xml
<variable name="ANDROID_USE_AD_ID" value="true" />
```

An application must not use an advertising identifier if **at least one** of the following conditions is true:
- The app’s target audience includes **only children**, as defined in the [Families Policy](https://support.google.com/googleplay/android-developer/answer/9893335?sjid=10683822576513227860-EU).
- The app is being built for **devices that do not use Google Play Services** (e.g. Amazon or Huawei devices).

</TabItem>
<TabItem label="iOS" value="ios">
To use the [App Tracking Transparency authorization request](https://developer.apple.com/documentation/bundleresources/information_property_list/nsusertrackingusagedescription) for accessing the IDFA, add plugin variable `IOS_USER_TRACKING_USAGE` to the `config.xml` with a custom message describing your usage. Below is an example description text:

```xml
<variable name="IOS_USER_TRACKING_USAGE" value="Your data will remain confidential and will only be used to provide you a better and personalised ad experience" />
```

<AccordionGroup>
<Accordion title="Usage description examples">

- Your data will remain confidential and will only be used to provide you a better and personalised ad experience
- Your data will be used to provide you a better and personalised ad experience
- Your data will be used to create a customized experience tailored to your interests
- Allowing tracking will enable more personalized ads for you
- We try to show ads for apps and products that will be most interesting to you based on the apps you use
- This identifier will be used to deliver personalized ads to you
- This only uses device info for more interesting and relevant ads

</Accordion>
</AccordionGroup>

</TabItem>
</Tabs>

## Add CAS.AI Cordova plugin
Include the CAS.AI plugin for Cordova in your project with cordova command:
```shell
cordova plugin add cordova-plugin-casai
```

You can also specify all variables directly in the `plugin add` command by adding `--variable name=value` for each variable.

```shell
cordova plugin add cordova-plugin-casai --variable IOS_CAS_ID=demo
```

<Info>
To apply changes to the plugin variables, you need to remove and then re-add the plugin.
</Info>

```shell
cordova plugin rm cordova-plugin-casai --nosave && cordova plugin add cordova-plugin-casai
```

<Card title="Subscribe" icon="github" href="https://github.com/cleveradssolutions/CAS-Cordova/subscription">
Subscribe to receive notifications about CAS updates.
</Card>
```

### CAS.AI plugin for Flutter

Source: https://production.docs.page/docs/flutter

```mdx

Integrating CAS SDK into an app is the first step toward displaying ads and earning revenue. 
Once you've integrated and initialized the SDK, you can choose an ad format and follow the steps to implement it.

## Prerequisites
Make sure that your app's build file uses the following values:
- Use Flutter `3.0.0` or higher
- For Android:
  - Minimum API level `{{ min.api }}` or higher
- For iOS:
  - Use Xcode `{{ min.xcode }}` or higher
  - Minimum Target iOS version `{{ min.ios }}` or higher
  - Flutter `3.47` and newer build the plugin as a Swift package. Earlier versions, and projects that
    turn Swift Package Manager off, keep using CocoaPods

## Import CAS.AI Mobile Ads package
Include the [CAS.AI plugin for Flutter](https://pub.dev/packages/clever_ads_solutions/install) in your Flutter project.

With Flutter command:
```shell
flutter pub add clever_ads_solutions
```

<Card title="Subscribe" icon="github" href="https://github.com/cleveradssolutions/CAS-Flutter/subscription">
Subscribe to receive notifications about CAS updates.
</Card>

Now in your Dart code, you can use:
```dart
import 'package:clever_ads_solutions/clever_ads_solutions.dart';
```

## Platform specific setup
To monetize your app using CAS.AI mediation, in addition to importing the package, you need to configure your Android and iOS projects by using the **CAS Gradle plugin** for Android and a **Ruby CAS script** for iOS.  

<Tabs groupId="platform">
<TabItem label="Android" value="android">
The CAS Android SDK provide a Gradle Plugin to simplify and automate certain integration steps.
Our plugin will automatically add mediated network dependencies to your project, which you configure in an `cas { }` block.

In your Android app Gradle file (usually `<project>/android/app/build.gradle`), add the `com.cleveradssolutions.gradle-plugin` inside the `plugins` block.
```kotlin
plugins {
  id("com.android.application") // before CAS plugin
  id("com.cleveradssolutions.gradle-plugin") version "{{ versions.android }}"
}

cas {
  // Plugin configuration
}
```

<Success>
Make sure to update the CAS Gradle plugin version whenever you update the CAS Flutter package. The CASGradle plugin version matches the version of [the CAS Android SDK](https://github.com/cleveradssolutions/CAS-Android/releases). For detailed setup instructions, visit [the CAS Android repository](android#integration-options).
</Success>
</TabItem>

<TabItem label="iOS" value="ios">
The Ruby script performs automatic configuration of your iOS project. To apply it, follow the steps outlined below.
1. Download the <a href="https://github.com/cleveradssolutions/CAS-iOS/releases/download/{{ versions.iosconfig }}/casconfig.rb">casconfig.rb</a>  
2. Place the script in ios app directory `<project>/ios`
3. Open the terminal window and go to `ios` directory:
```
cd ios
```
4. Run ruby script with your app CAS ID:
```
ruby casconfig.rb <CAS ID>
```

<AccordionGroup>
<Accordion title="What is CAS ID in iOS?">

In most cases, a CASID is the same as your app store ID.  
You can find an app store ID in the URL of your app’s Apple App Store URL. For example, the URL is `apps.apple.com/us/app/id123456789` then app store ID is `123456789`.  
 
If you haven't created an CAS account and registered an app yet, now's a great time to do so at https://cas.ai  
If you just want to experiment or test the SDK, you can skip the configuration your project.

</Accordion>
</AccordionGroup>

<Success>
Repeat the script before every update of the app to make sure you are using up-to-date configurations. For more details about the script and its updates, visit [the CAS iOS repository🔗](https://github.com/cleveradssolutions/CAS-iOS/tree/master/Script%20XCodeConfig).
</Success>

### Add the CAS iOS SDK
Flutter `3.47` and newer build the plugin as a Swift package and wire it into the `Runner` target for you.
Projects on an earlier Flutter, or with Swift Package Manager turned off, keep using CocoaPods. Both paths
install the same SDK and are configured by the same script above.

<Tabs groupId="iosdeps">
<TabItem label="Swift Package Manager" value="spm">
There is nothing to add for the SDK itself: `flutter build ios` resolves the CAS iOS Swift Package through the
plugin and links it into `Runner`.

The plugin links the SDK alone. Ad network adapters are separate products of the same package: add the ones
your app needs to the `Runner` target, see [Choose Mediated Networks](#choose-mediated-networks) below.

<Info>
Swift Package Manager is enabled by default since Flutter `3.47`. Run `flutter config` to see the state of the
setting, and `flutter config --no-enable-swift-package-manager` to fall back to CocoaPods. Flutter has
announced that disabling it will not be allowed in a future release.
</Info>
</TabItem>

<TabItem label="CocoaPods" value="cocoapods">
The `<project>/ios/Podfile` is a specification that describes the dependencies of your iOS project. 
All CAS frameworks are hosted and distributed through their own source repository. Please add CAS source repository url to the beginning of the Podfile:
```ruby
source 'https://github.com/CocoaPods/Specs.git'
source 'https://github.com/cleveradssolutions/CAS-Specs.git'
```

Mediation dependencies should be added to the `target` block, before the `end` line.
```ruby
target 'Runner' do
    pod ...
    ...
end
```
Run `pod update` terminal command inside the `ios` directory after modifying the `Podfile`.

<Success>
Make sure to update the CAS pods version whenever you update the CAS Flutter package. The Ads Solution pods version matches the version of [the CAS iOS SDK](https://github.com/cleveradssolutions/CAS-iOS/releases).
</Success>
</TabItem>
</Tabs>

<Warning>
Pick one dependency manager for CAS.AI, not both. A project that keeps the Swift Package and also adds CAS pods
links two copies of the SDK and fails to build with duplicate symbols. To take the adapters as pods, turn
Swift Package Manager off first.
</Warning>

</TabItem>
</Tabs>

## Choose Mediated Networks
<Warning>
CAS.AI is a mediation SDK with no built-in live ad inventory. At least one ad network adapter or solution must be integrated before publishing to display ads and generate revenue.
</Warning>

Choose an integration path based on your app's target audience. If you're unsure which solution best fits your application, please contact your account manager.

<Info>
During development, you can test ad formats using [Test Ads](flutter/enabling-test-ads) without adding any ad network SDKs.
</Info>

Check the details of the ad network adapters supported by CAS.AI Mediation in the [Android repository](https://github.com/cleveradssolutions/CAS-Android/blob/master/Adapters/README.md) and [iOS repository](https://github.com/cleveradssolutions/CAS-iOS/blob/master/Adapters/README.md) tables.

### Android
The CAS Gradle plugin offers curated solutions that CAS.AI keeps up to date.

<AccordionGroup>
<Accordion defaultOpen title="Optimal Ads Solution">

Recommended for **most applications** targeting a **general or mixed audience**. Includes a broad set of stable, high-performance networks.

```kotlin
// <project>/android/app/build.gradle
cas {
    includeOptimalAds = true
}
```

</Accordion>

<Accordion title="Families Ads Solution">

Required for applications **directed exclusively at children**, in accordance with the [Google Play Families Policy](https://support.google.com/googleplay/android-developer/answer/12918983?hl=en) and fully compatible with the [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy).

```kotlin
// <project>/android/app/build.gradle
cas {
    includeFamiliesAds = true
}
```

</Accordion>

<Accordion title="VPN Compliant Ads Solutions">

Designed specifically for applications that provide VPN or proxy services. This solution includes partner networks that comply with VPN-related traffic policies and restrictions.

```kotlin
// <project>/android/app/build.gradle
cas {
    includeVPNCompliantAds = true
}
```

</Accordion>

<Accordion title="Choice mediation adapters">

Advanced publishers familiar with ad network integrations can configure their own set of adapters. For detailed instructions on how to integrate specific adapters into your app, refer to the [Android page](android/mediated-networks).

</Accordion>
</AccordionGroup>

### iOS
How you add a network depends on the dependency manager your project uses, see
[Add the CAS iOS SDK](#add-the-cas-ios-sdk) above.

<Tabs groupId="iosdeps">
<TabItem label="Swift Package Manager" value="spm">
The Swift Package exposes a curated solution product that pulls a whole set of networks at once, and one
library product per network for a hand-picked set. Adding a network is an Xcode step, not a code change: the
product carries the adapter binary and the CAS.AI SDK picks it up at runtime.

<Steps>
<Step title="Add the CAS package to the Runner target">
Open `<project>/ios/Runner.xcworkspace` in Xcode, select **File ▸ Add Package Dependencies…** and enter the CAS
Git repository URL into the **Search or Enter Package URL** field:
```
https://github.com/cleveradssolutions/CAS-iOS
```
Set the **Dependency Rule** to **Up to Next Minor Version**, enter `{{ versions.ios }}` and click **Add Package**.
</Step>
<Step title="Pick the products">
Xcode then asks which library products to add to which target. Pick them from the list below and add them to
the **Runner** target.

The CAS.AI SDK itself arrives through the plugin, so `CleverAdsSolutionsSPM` does not have to be checked here.
Nothing has to be imported or called in Dart or Swift for an adapter to work.
</Step>
</Steps>

<AccordionGroup>
<Accordion defaultOpen title="Optimal Ads Solution">

Recommended for **most applications** targeting a **general or mixed audience**. Includes a broad set of stable, high-performance networks.

Add the `AdsOptimalSolutions` product to the **Runner** target.

> Networks included: Google Ads, Unity Ads, IronSource, Liftoff Monetize, InMobi, Mintegral, AppLovin, Pangle, Bigo, Yango Ads, Audience Network, YSO Network, CAS Exchange, Maticoo.

</Accordion>

<Accordion title="Families Ads Solution">

Required for applications **directed exclusively at children**, in accordance with the [Google Play Families Policy](https://support.google.com/googleplay/android-developer/answer/12918983?hl=en) and fully compatible with the [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy).

Add the `AdsFamiliesSolutions` product to the **Runner** target.

> Networks included: Google Ads, Unity Ads, IronSource, Liftoff Monetize, InMobi, Chartboost, Kidoz, Mintegral, Yango Ads.

</Accordion>

<Accordion title="VPN Compliant Ads Solutions">

Designed specifically for applications that provide VPN or proxy services. This solution includes partner networks that comply with VPN-related traffic policies and restrictions.

Add the `AdsVPNCompliantSolutions` product to the **Runner** target.

> Networks included: Google Ads, Unity Ads, IronSource, Liftoff Monetize, InMobi, Mintegral, Bigo, Yango Ads, YSO Network, Monetrix.

</Accordion>

<Accordion title="Choice mediation adapters">

Advanced publishers familiar with ad network integrations can configure their own set of adapters. Add one
`CASMediation*` product per network to the **Runner** target.

The library product of a network is its name in the
[adapters table of the CAS iOS repository](https://github.com/cleveradssolutions/CAS-iOS/blob/master/Adapters/README.md)
prefixed with `CASMediation`, for example `CASMediationGoogleAds` for the `GoogleAds` row. The one exception is
`CASExchange`, whose product is `CASMediationExchange`. Xcode lists the exact products when you add the package,
so you never have to guess.

The **SPM** column of that table says whether the adapter is distributed through Swift Package Manager. A few
are not, because of limitations of the ad frameworks themselves. If you need one of those, use CocoaPods
instead.

</Accordion>
</AccordionGroup>

<Info>
The solution products arrived in CAS `4.8.3`. On an earlier version of the package, add the `CASMediation*`
products of a solution one by one.
</Info>

To change the selection later, select the project in the Project navigator, select the **Runner** target, open
the **General** tab and edit **Frameworks, Libraries, and Embedded Content**.
</TabItem>

<TabItem label="CocoaPods" value="cocoapods">
Add the solution to the `target 'Runner'` block of `<project>/ios/Podfile`, then run `pod update` inside the
`ios` directory.

<AccordionGroup>
<Accordion defaultOpen title="Optimal Ads Solution">

Recommended for **most applications** targeting a **general or mixed audience**. Includes a broad set of stable, high-performance networks.

```ruby
# <project>/ios/Podfile
pod 'CleverAdsSolutions-SDK/Optimal', '{{ versions.ios }}'
```

</Accordion>

<Accordion title="Families Ads Solution">

Required for applications **directed exclusively at children**, in accordance with the [Google Play Families Policy](https://support.google.com/googleplay/android-developer/answer/12918983?hl=en) and fully compatible with the [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy).

```ruby
# <project>/ios/Podfile
pod 'CleverAdsSolutions-SDK/Families', '{{ versions.ios }}'
```

</Accordion>

<Accordion title="VPN Compliant Ads Solutions">

Designed specifically for applications that provide VPN or proxy services. This solution includes partner networks that comply with VPN-related traffic policies and restrictions.

```ruby
# <project>/ios/Podfile
pod 'CleverAdsSolutions-SDK/VPNCompliant', '{{ versions.ios }}'
```

</Accordion>

<Accordion title="Choice mediation adapters">

Advanced publishers familiar with ad network integrations can configure their own set of adapters. For detailed instructions on how to integrate specific adapters into your app, refer to the [iOS page](ios/mediated-networks).

</Accordion>
</AccordionGroup>
</TabItem>
</Tabs>

<Warning>
The Android and iOS network sets are configured separately and are expected to differ. Not every network ships
an adapter for both platforms, store policies for child-directed apps do not approve the same networks, and
individual iOS adapters raise the minimum deployment target. Pick the networks per platform rather than
mirroring one list onto the other.
</Warning>

## Advertising Identifier
CAS Mediation uses the [Google Advertising ID](https://support.google.com/googleplay/android-developer/answer/6048248?hl=en) and [Apple Identifier for Advertisers (IDFA)](https://developer.apple.com/documentation/adsupport) to deliver personalized and more relevant ads to each user.  
To enable the use of the Advertising ID in your app, you need to complete the following setup steps.

<AccordionGroup>
<Accordion title="Android Google Adverision ID">
CAS Mediation allows you to easily enable or disable the use of the Advertising ID, depending on your app’s privacy requirements.

```kotlin
// <project>/android/app/build.gradle
cas {
    useAdvertisingId = true
}
```

An application must not use an advertising identifier if **at least one** of the following conditions is true:
- The app’s target audience includes **only children**, as defined in the [Families Policy](https://support.google.com/googleplay/android-developer/answer/9893335?sjid=10683822576513227860-EU).
- The app is being built for **devices that do not use Google Play Services** (e.g. Amazon or Huawei devices).

</Accordion>

<Accordion title="iOS User Tracking Usage description">

To use the App Tracking Transparency authorization request for accessing the IDFA, update your `<project>/ios/Runner/Info.plist` to add the [NSUserTrackingUsageDescription](https://developer.apple.com/documentation/bundleresources/information_property_list/nsusertrackingusagedescription) key (Name in Xcode Property List Editor: `Privacy - Tracking Usage Description`) with a custom message describing your usage. Below is an example description text:
```xml
<key>NSUserTrackingUsageDescription</key>
<string>Your data will remain confidential and will only be used to provide you a better and personalised ad experience</string>
```

- Your data will remain confidential and will only be used to provide you a better and personalised ad experience
- Your data will be used to provide you a better and personalised ad experience
- Your data will be used to create a customized experience tailored to your interests
- Allowing tracking will enable more personalized ads for you
- We try to show ads for apps and products that will be most interesting to you based on the apps you use
- This identifier will be used to deliver personalized ads to you
- This only uses device info for more interesting and relevant ads

</Accordion>
<Accordion title="iOS Localizing Usage description (optional)">

To optimize performance and to improve the user experience, you can localize the `NSUserTrackingUsageDescription` string. Please follow the [Documentation > Xcode > Localization](https://developer.apple.com/documentation/xcode/localization) instructions to learn how to localize your app.  
The table below gives you a variety of localizations that you can use at your discretion.

| Locale          | Description                            |
|-----------------|----------------------------------------------------------------------------|
| English (en)    | Your data will remain confidential and will only be used to provide you a better and personalised ad experience                               |
| German (de)     | Ihre Daten bleiben vertraulich und werden nur dazu verwendet, Ihnen ein besseres und personalisiertes Werbeerlebnis zu bieten                 |
| French (fr)     | Vos données resteront confidentielles et seront utilisées uniquement pour vous offrir une expérience publicitaire meilleure et personnalisée  |
| Spanish (es)    | Sus datos permanecerán confidenciales y solo se utilizarán para brindarle una experiencia publicitaria mejor y personalizada                  |
| Ukrainian (uk)  | Ваші дані залишатимуться конфіденційними та використовуватимуться лише для надання вам кращої та персоналізованої реклами                     |
| Russian (ru)    | Ваши данные останутся конфиденциальными и будут использоваться только для предоставления вам более качественной и персонализированной рекламы |
| Portuguese (pt) | Seus dados permanecerão confidenciais e serão usados apenas para lhe proporcionar uma experiência publicitária melhor e personalizada         |
| Japanese (ja)   | お客様のデータは機密として保持され、より優れたパーソナライズされた広告エクスペリエンスを提供するためにのみ使用されます |

</Accordion>
</AccordionGroup>
```

### CAS.AI Developer Docs

Source: https://production.docs.page/docs/general

```mdx

CAS.AI (Clever Ads Solutions) provides a powerful monetization platform for mobile developers.
CAS.AI Mediation allows you to serve ads from multiple ad networks through a single integration.
The CAS SDK helps you maximize fill rates and boost monetization by sending ad requests to multiple networks, ensuring the best available one delivers the ad.

## Platform
Select one of the following platforms to get started with our SDK

<CardGroup>
  <Card title="Android" icon="android" href="android">
    Version: `{{ versions.android }}`
  </Card>
  <Card title="iOS" icon="apple" href="ios">
    Version: `{{ versions.ios }}`
  </Card>
  <Card title="Unity" icon="unity" href="unity">
    Version: `{{ versions.unity }}`
  </Card>
  <Card title="Flutter" icon="flutter" href="flutter">
    Version: `{{ versions.flutter }}`
  </Card>
  <Card title="Kotlin Multiplatform" icon="k" href="kmp">
    Version: `{{ versions.kmp }}`
  </Card>
  <Card title="Unreal" icon="unreal-engine" href="unreal">
    Version: `{{ versions.unreal }}`
  </Card>
  <Card title="ReactNative" icon="react" href="reactnative">
    Version: `{{ versions.reactnative }}`
  </Card>
  <Card title="Cordova" icon="simplybuilt" href="cordova">
    Version: `{{ versions.cordova }}`
  </Card>
  <Card title="Construct" icon="c" href="construct">
    Version: `{{ versions.construct }}`
  </Card>
</CardGroup>

## Alternative platform
The following table lists libraries for using CAS.AI mediation on game engines and development frameworks. 
While we recommend these libraries for developers using CAS.AI on a preferred platform, these platforms are not official, and which CAS.AI support doesn't cover. 
For support using these libraries, file an issue through the links in GitHub Source.

<CardGroup>
  <Card title="Godot" icon="github" href="https://github.com/damnedpie/godot-cas">
    by damnedpie
  </Card>
  <Card title="Defold" icon="github" href="https://github.com/Lerg/extension-cas">
    by Lerg
  </Card>
  <Card title="Solar 2D" icon="github" href="https://github.com/solar2d/com.cleveradssolutions-plugin.cas/blob/master/docs/CleverAdsSolutions/index.markdown">
    deprecated
  </Card>
</CardGroup>
```

### CAS.AI iOS Framework

Source: https://production.docs.page/docs/ios

```mdx

Integrating CAS SDK into an app is the first step toward displaying ads and earning revenue. 
Once you've integrated and initialized the SDK, you can choose an ad format and follow the steps to implement it.

## App prerequisites
- Use Xcode `{{ min.xcode }}` or higher
- Target minimum iOS `{{ min.ios }}` or higher

<Card title="Subscribe" icon="github" href="https://github.com/cleveradssolutions/CAS-iOS/subscription">
Subscribe to receive notifications about CAS updates.
</Card>

## Add the SDK to your project
CAS.AI ships for both Swift Package Manager and CocoaPods. Pick the dependency manager your project already uses — everything after this step is the same for both.

<Tabs groupId="ios-dependency-manager">
<TabItem value="spm" label="Swift Package Manager">

The [Swift Package Manager](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app) is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system, automating the process of downloading, compiling, and linking dependencies.

#### Add the CAS package to your project
1. Select **File > Add Package Dependencies**
2. Enter the CAS Git repository URL into the **Search or Enter Package URL** field:

   ```
   https://github.com/cleveradssolutions/CAS-iOS
   ```
3. Specify the **Up to Next Minor Version**: `{{ versions.ios }}`
4. Click **Add Package**

Xcode then asks which products of the package to add to your app target. Pick them in [Choose Mediated Networks](#choose-mediated-networks) below.

</TabItem>
<TabItem value="cocoapods" label="CocoaPods">

[CocoaPods](http://guides.cocoapods.org/using/getting-started.html) is a dependency manager for Objective-C and Swift; it automates and simplifies the SDK integration process.

#### Open your project's Podfile
The `Podfile` is a specification that describes the dependencies of the targets of one or more Xcode projects. You could use a `pod init` command to create the `Podfile` with smart defaults.

#### Add CAS pods source url to the beginning of the file:
```ruby
source 'https://github.com/CocoaPods/Specs.git'
source 'https://github.com/cleveradssolutions/CAS-Specs.git'
```

#### Use pods as frameworks
```ruby
use_frameworks!
```

</TabItem>
</Tabs>

### Choose Mediated Networks
<Warning>
CAS.AI is a mediation SDK with no built-in live ad inventory. At least one ad network adapter or solution must be integrated before publishing to display ads and generate revenue.
</Warning>

Choose an integration path based on your app's target audience. If you're unsure which solution best fits your application, please contact your account manager.

<Info>
During development, you can test ad formats using [Test Ads](ios/enabling-test-ads) without adding any ad network SDKs.
</Info>

<Tabs groupId="ios-dependency-manager">
<TabItem value="spm" label="Swift Package Manager">

<AccordionGroup>
<Accordion defaultOpen title="Optimal Ads Solution">

Recommended for **most applications** targeting a **general or mixed audience**. Includes a broad set of stable, high-performance networks.

Add the `AdsOptimalSolutions` product to your app target.

> Networks included: Google Ads, Unity Ads, IronSource, Liftoff Monetize, InMobi, Mintegral, AppLovin, Pangle, Bigo, Yango Ads, Audience Network, YSO Network, CAS Exchange, Maticoo.

</Accordion>
<Accordion title="Families Ads Solution">

Required for applications **directed exclusively at children** and fully compatible with the [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy). 

Add the `AdsFamiliesSolutions` product to your app target.

> Networks included: Google Ads, Unity Ads, IronSource, Liftoff Monetize, InMobi, Chartboost, Kidoz, Mintegral, Yango Ads.

<Info>
The families ads solution is NOT intended for apps in [Apple Kids Category](/general/apple-kids-category).
</Info>

</Accordion>
<Accordion title="VPN Compliant Ads Solutions">

Designed specifically for applications that provide VPN or proxy services. This solution includes partner networks that comply with VPN-related traffic policies and restrictions. 

Add the `AdsVPNCompliantSolutions` product to your app target.

> Networks included: Google Ads, Unity Ads, IronSource, Liftoff Monetize, InMobi, Mintegral, Bigo, Yango Ads, YSO Network, Monetrix.

</Accordion>
<Accordion title="Choice networks">

Advanced publishers who are familiar with ad network integrations can choose their own set of adapters. If you have any questions or need assistance, please contact your account manager.  

Add the `CASMediation…` product of every network you need to your app target. Each adapter product already brings the CAS base framework with it.

Add the `CleverAdsSolutionsSPM` product on its own only when you integrate the SDK without any ad network, for example to try [Test Ads](ios/enabling-test-ads).

Follow the instructions on the [Mediated Networks](ios/mediated-networks) page.

</Accordion>
</AccordionGroup>

<Info>
The Ads Solutions products for Swift Package Manager are available starting with CAS `4.8.3`. On earlier versions, add the `CASMediation…` products one by one.
</Info>

</TabItem>
<TabItem value="cocoapods" label="CocoaPods">

<AccordionGroup>
<Accordion defaultOpen title="Optimal Ads Solution">

Recommended for **most applications** targeting a **general or mixed audience**. Includes a broad set of stable, high-performance networks.

```ruby
pod 'CleverAdsSolutions-SDK/Optimal', '{{ versions.ios }}'
```

> Networks included: Google Ads, Unity Ads, IronSource, Liftoff Monetize, InMobi, Mintegral, AppLovin, Pangle, Bigo, Yango Ads, Audience Network, YSO Network, CAS Exchange, Maticoo.

</Accordion>
<Accordion title="Families Ads Solution">

Required for applications **directed exclusively at children** and fully compatible with the [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy). 

```ruby
pod 'CleverAdsSolutions-SDK/Families', '{{ versions.ios }}'
```

> Networks included: Google Ads, Unity Ads, IronSource, Liftoff Monetize, InMobi, Chartboost, Kidoz, Mintegral, Yango Ads.

<Info>
The families ads solution is NOT intended for apps in [Apple Kids Category](/general/apple-kids-category).
</Info>

</Accordion>
<Accordion title="VPN Compliant Ads Solutions">

Designed specifically for applications that provide VPN or proxy services. This solution includes partner networks that comply with VPN-related traffic policies and restrictions. 

```ruby
pod 'CleverAdsSolutions-SDK/VPNCompliant', '{{ versions.ios }}'
```

> Networks included: Google Ads, Unity Ads, IronSource, Liftoff Monetize, InMobi, Mintegral, Bigo, Yango Ads, YSO Network, Monetrix.

</Accordion>
<Accordion title="Choice networks">

Advanced publishers who are familiar with ad network integrations can choose their own set of adapters. If you have any questions or need assistance, please contact your account manager.  

When you are not using the solution pods, you must add a `CleverAdsSolutions-Base` pod for the CAS base framework. 
```ruby
pod 'CleverAdsSolutions-Base', '{{ versions.ios }}'
```

Follow the instructions on the [Mediated Networks](ios/mediated-networks) page.

</Accordion>
</AccordionGroup>

</TabItem>
</Tabs>

### Check project’s build settings
- Open Xcode `<Project>.xcodeproj`
- Go to the Build Settings section for the app target
- Find the `OTHER_LDFLAGS` property, if customized.

<Tabs groupId="ios-dependency-manager">
<TabItem value="spm" label="Swift Package Manager">

Make sure that `$(inherited)` and the `-ObjC` flag are at the beginning of the list. Swift Package Manager has no `xcconfig` to set the flag for you, and without it the linker drops the Objective-C categories the adapters ship.

</TabItem>
<TabItem value="cocoapods" label="CocoaPods">

Make sure the `$(inherited)` flag is at the beginning of the list, so that the settings CocoaPods generates are applied.

</TabItem>
</Tabs>

### Resolve the dependencies

<Tabs groupId="ios-dependency-manager">
<TabItem value="spm" label="Swift Package Manager">

Xcode resolves the packages the moment you add them. To pick up a new version later, select **File > Packages > Resolve Package Versions**.

Keep opening the `<Project>.xcodeproj` file as usual — Swift Package Manager needs no workspace.

</TabItem>
<TabItem value="cocoapods" label="CocoaPods">

Open the terminal window and run:
```sh
cd into/your/project/folder
```
Run pod install with repo update:
```sh
pod update
```

Make sure that after `Pod installation complete` in the terminal, there are no issues that need to be fixed. Repeat the installation after resolving issues.

<Info>
Read more about [Cocoapods troubleshooting](https://guides.cocoapods.org/using/troubleshooting.html#using-the-cocoapods-project).
</Info>

Make sure to always open the Xcode workspace instead of the project file when building your project:
```sh
open <Project>.xcworkspace
```

</TabItem>
</Tabs>

## Manual download
For projects where you cannot use CocoaPods during Xcode build, you need to manually collect all frameworks from the CAS Pod dependencies and add them to the project. Our script, which can be found in the repository [here](https://github.com/cleveradssolutions/CAS-iOS/tree/master/Script%20PodFrameworks), will assist you with this process.

## Configure Info.plist
Your project `Info.plist` requires additional configurations that can be performed automatically by a special script.
1. Download the <a href="https://github.com/cleveradssolutions/CAS-iOS/releases/download/{{ versions.iosconfig }}/casconfig.rb">casconfig.rb</a>  
2. Place the script in directory with the app `.xcodeproj` 
3. Open the terminal window and run command:
```
cd into/your/project/folder
```
5. Run ruby script:
```
ruby casconfig.rb <CAS_ID>
```

<AccordionGroup>
<Accordion title="What is CAS ID?">

In most cases, a CASID is the same as your app store ID.  
You can find an app store ID in the URL of your app’s Apple App Store URL. For example, the URL is `apps.apple.com/us/app/id123456789` then app store ID is `123456789`.  
 
If you haven't created an CAS account and registered an app yet, now's a great time to do so at https://cas.ai  
If you just want to experiment or test the SDK, you can skip the configuration your project.

</Accordion>

<Accordion title="What does the script do?">

The script automatically performs the following integration steps:
- [x] Set [AdAttributionKit and SKAdNetwork Support](general/apple-ad-attribution) to Info.plist
- [x] Set [App Transport Security](ios/manually-configure-project) to Info.plist
- [X] Set User Tracking usage description to Info.plist
- [x] Set [Google Ads App ID](ios/manually-configure-project) to Info.plist
- [x] Set Delay app measurement to Info.plist
- [x] [Link the CAS project](ios/manually-configure-project)

</Accordion>
</AccordionGroup>

For more details about the script and its updates, please refer to the [the CAS iOS repository](https://github.com/cleveradssolutions/CAS-iOS/tree/master/Script%20XCodeConfig).

<Info>
Repeat the script before every update of the application to make sure you are using up-to-date configurations.
</Info>

<Success>  
Instead of using the `casconfig.rb` script, you can manually complete [additional steps to configure your project](ios/manually-configure-project). (Not recomended)
</Success>

### User Tracking usage description
To display the App Tracking Transparency authorization request for accessing the IDFA, update your `Info.plist` to add the [NSUserTrackingUsageDescription](https://developer.apple.com/documentation/bundleresources/information_property_list/nsusertrackingusagedescription) key with a custom message describing your usage. Below is an example description text:
```xml
<key>NSUserTrackingUsageDescription</key>
<string>Your data will remain confidential and will only be used to provide you a better and personalised ad experience</string>
```

<Info>
Name in Xcode Property List Editor: Privacy - Tracking Usage Description
</Info>

<AccordionGroup>
<Accordion title="Usage description examples">

- Your data will remain confidential and will only be used to provide you a better and personalised ad experience
- Your data will be used to provide you a better and personalised ad experience
- Your data will be used to create a customized experience tailored to your interests
- Allowing tracking will enable more personalized ads for you
- We try to show ads for apps and products that will be most interesting to you based on the apps you use
- This identifier will be used to deliver personalized ads to you
- This only uses device info for more interesting and relevant ads

</Accordion>
<Accordion title="Localizing Usage description (optional)">

To optimize performance and to improve the user experience, you can localize the `NSUserTrackingUsageDescription` string. Please follow the [Documentation > Xcode > Localization](https://developer.apple.com/documentation/xcode/localization) instructions to learn how to localize your app.  
The table below gives you a variety of localizations that you can use at your discretion. 

| Locale | Description |
| ----------- | ----------- |
| English (en) | Your data will remain confidential and will only be used to provide you a better and personalised ad experience |
| German (de) | Ihre Daten bleiben vertraulich und werden nur dazu verwendet, Ihnen ein besseres und personalisiertes Werbeerlebnis zu bieten |
| French (fr) | Vos données resteront confidentielles et seront utilisées uniquement pour vous offrir une expérience publicitaire meilleure et personnalisée |
| Spanish (es) | Sus datos permanecerán confidenciales y solo se utilizarán para brindarle una experiencia publicitaria mejor y personalizada |
| Ukrainian (uk) | Ваші дані залишатимуться конфіденційними та використовуватимуться лише для надання вам кращої та персоналізованої реклами |
| Russian (ru) | Ваши данные останутся конфиденциальными и будут использоваться только для предоставления вам более качественной и персонализированной рекламы |
| Portuguese (pt) | Seus dados permanecerão confidenciais e serão usados apenas para lhe proporcionar uma experiência publicitária melhor e personalizada |
| Japanese (ja) | お客様のデータは機密として保持され、より優れたパーソナライズされた広告エクスペリエンスを提供するためにのみ使用されます |

</Accordion>
</AccordionGroup>
```

### CAS.AI plugin for Kotlin Multiplatform

Source: https://production.docs.page/docs/kmp

```mdx

Integrating CAS SDK into an app is the first step toward displaying ads and earning revenue.
Once you've integrated and initialized the SDK, you can choose an ad format and follow the steps to implement it.

The plugin exposes a single `expect` API from `commonMain`, backed by the native CAS.AI SDK on each platform.
Banner and Native ads are also available as Compose Multiplatform composables, so the whole integration can live in shared code.

## Prerequisites
Make sure that your app's build files use the following values:
- Use Kotlin `{{ min.kotlin }}` or higher
- Use Compose Multiplatform `{{ min.compose }}` or higher, if you use the ad composables
- For Android:
  - Minimum API level `{{ min.api }}` or higher
  - Compile SDK version of `{{ min.targetapi }}` or higher
- For iOS:
  - Use Xcode `{{ min.xcode }}` or higher
  - Minimum Target iOS version `{{ min.ios }}` or higher
  - Supported targets: `iosArm64` and `iosSimulatorArm64`. 
    > There is no x86_64 simulator target, so a Mac with an Intel processor cannot run the simulator build

## Import CAS.AI Mobile Ads library
Add the CAS.AI Kotlin Multiplatform library to the common source set of your shared module.

```kotlin
// <project>/shared/build.gradle.kts
kotlin {
    sourceSets {
        commonMain.dependencies {
            implementation("com.cleveradssolutions:cas-kmp:{{ versions.kmp }}")
        }
    }
}
```

<Card title="Subscribe" icon="github" href="https://github.com/cleveradssolutions/CAS-KMP/subscription">
Subscribe to receive notifications about CAS updates.
</Card>

Now in your common Kotlin code, you can use:
```kotlin
import com.cleveradssolutions.plugin.kmp.*
```

<Info>
The Android artifact declares the CAS.AI Android SDK as `compileOnly`, so the SDK itself and the
mediation adapters are resolved by your application. The platform setup below adds them.
</Info>

## Platform specific setup
To monetize your app using CAS.AI mediation, in addition to importing the library, you need to configure
your Android and iOS projects by using the **CAS Gradle plugin** for Android and the **CAS Swift Package** for iOS.

<Tabs groupId="platform">
<TabItem label="Android" value="android">
The CAS Android SDK provides a Gradle Plugin to simplify and automate certain integration steps.
Our plugin will automatically add mediated network dependencies to your project, which you configure in a `cas { }` block.

Apply `com.cleveradssolutions.gradle-plugin` to the module that holds the Android target, inside the `plugins` block
and after the Android plugin itself.

```kotlin
// <project>/shared/build.gradle.kts
plugins {
    kotlin("multiplatform")
    id("com.android.application") // before CAS plugin
    id("com.cleveradssolutions.gradle-plugin") version "{{ versions.android }}"
}

cas {
    // Plugin configuration
}
```

#### Add Maven repositories
Several ad networks do not publish their Android SDK to Maven Central, so their adapters cannot be resolved
without the network's own repository. The CAS Gradle plugin does not add them for you.

Copy the repositories block from [Add Maven repositories](android#add-maven-repositories) into the
`dependencyResolutionManagement` of your `settings.gradle.kts`.

<Error>
Without them the Android build fails while resolving dependencies, with a message such as
`Could not find com.mbridge.msdk.oversea:mbridge_android_sdk`, and the same for `com.pangle.global`,
`com.ysocorp` and the other networks that host their own artifacts.
</Error>

<Success>
Make sure to update the CAS Gradle plugin version whenever you update the CAS Kotlin Multiplatform library. The CAS Gradle plugin version matches the version of [the CAS Android SDK](https://github.com/cleveradssolutions/CAS-Android/releases). For detailed setup instructions, visit [the CAS Android repository](android#integration-options).
</Success>
</TabItem>

<TabItem label="iOS" value="ios">
The CAS iOS SDK is distributed as a **Swift Package**. Add it to the Xcode project that hosts your shared module.

<Steps>
<Step title="Add the package dependency">
In Xcode, select **File ▸ Add Package Dependencies…** and enter the CAS Git repository URL into the
**Search or Enter Package URL** field:
```
https://github.com/cleveradssolutions/CAS-iOS
```
</Step>
<Step title="Specify the version">
Set the **Dependency Rule** to **Up to Next Minor Version** and enter `{{ versions.kmpios }}`, then click **Add Package**.

Keep this version in step with the CAS Gradle plugin on Android. Both are updated together with the Kotlin
Multiplatform library.
</Step>
<Step title="Choose the library products">
Xcode then asks which library products to add to which target. Check `CleverAdsSolutionsSPM`, which is the
CAS.AI SDK itself, and one `CASMediation*` product per ad network you want to monetize with. The list of
products is in [Choose Mediated Networks](#choose-mediated-networks) below.

Nothing has to be imported or called in code for an adapter to work: each product carries the adapter binary,
and the CAS.AI SDK discovers it at runtime.
</Step>
</Steps>

Alternatively, if your Xcode project consumes a local Swift package of your own, declare the dependency in its
`Package.swift`:
```swift
dependencies: [
    .package(
        url: "https://github.com/cleveradssolutions/CAS-iOS",
        .upToNextMinor(from: "{{ versions.kmpios }}")
    )
]
```
The products then go into the dependencies of your target, see [Choose Mediated Networks](#choose-mediated-networks).

<Info>
The CAS.AI SDK is also published through CocoaPods. Swift Package Manager is the recommended option for
new projects and is the one these pages document. If your project already uses CocoaPods, follow
[the iOS integration page](ios) instead.
</Info>

### Deliver the Kotlin framework to Xcode
Your shared module is compiled into an Apple framework that the Xcode project links against. Declare the
framework binary in the shared module:

```kotlin
// <project>/shared/build.gradle.kts
kotlin {
    listOf(iosArm64(), iosSimulatorArm64()).forEach { iosTarget ->
        iosTarget.binaries.framework {
            baseName = "Shared"
            isStatic = true
        }
    }
}
```

Then connect it to Xcode with the direct integration mechanism of the Kotlin Gradle plugin:
1. In your Xcode project, select the application target and open the **Build Phases** tab.
2. Add a **New Run Script Phase** and move it **before** the **Compile Sources** phase.
3. Use the following script, where `shared` is the Gradle path of your shared module:
```shell
cd "$SRCROOT/.."
./gradlew :shared:embedAndSignAppleFrameworkForXcode
```
4. In **Build Settings**, add the framework output directory to **Framework Search Paths**:
```
$(SRCROOT)/../shared/build/xcode-frameworks/$(CONFIGURATION)/$(SDK_NAME)
```
5. Build the project once, then add `Shared.framework` under **Frameworks, Libraries, and Embedded Content** of the application target.

<Info>
See [Integration with the Xcode build](https://www.jetbrains.com/help/kotlin-multiplatform-dev/multiplatform-direct-integration.html) in the Kotlin Multiplatform documentation for the full description of this mechanism.
</Info>

### Configure the iOS project
The Xcode project needs a set of additional settings that CAS.AI maintains for you in a Ruby script, so that
they stay correct as the mediated networks change. The script configures:

- `SKAdNetworkItems` and the AdAttributionKit identifiers of every mediated network, in `Info.plist` (see [Apple Ad Attribution](general/apple-ad-attribution))
- `NSUserTrackingUsageDescription`, the App Tracking Transparency prompt text
- `GADApplicationIdentifier` and the Google delay app measurement flag
- App Transport Security
- `$(inherited)` and `-ObjC` in the **Other Linker Flags** of the project

<Error>
The adapters are discovered by class name at runtime. Without the `-ObjC` flag the linker strips their
Objective-C classes: the project builds and the SDK initializes, but every mediated network stays
unavailable and ads are never filled.
</Error>

<Steps>
<Step title="Download the script">

Download [casconfig.rb](https://github.com/cleveradssolutions/CAS-iOS/releases/download/{{ versions.iosconfig }}/casconfig.rb) and place it in the `iosApp` directory, next to the app `.xcodeproj`.

</Step>
<Step title="Run it with your CAS ID">
```shell
cd iosApp
ruby casconfig.rb <CAS ID>
```

The script can also live anywhere else, as long as you point it at the project:
```shell
ruby /path/to/casconfig.rb <CAS ID> --project=/path/to/iosApp.xcodeproj
```

Run `ruby casconfig.rb --help` to see the rest of its options.
</Step>
</Steps>

<Success>
Repeat the script before every update of the app to make sure you are using up-to-date configurations. For
details on what each setting does, and how to apply them by hand, see
[Manually configure project](ios/manually-configure-project).
</Success>

<AccordionGroup>
<Accordion title="What is CAS ID in iOS?">

In most cases, a CASID is the same as your app store ID.
You can find an app store ID in the URL of your app’s Apple App Store URL. For example, the URL is `apps.apple.com/us/app/id123456789` then app store ID is `123456789`.

If you haven't created an CAS account and registered an app yet, now's a great time to do so at https://cas.ai
If you just want to experiment or test the SDK, you can skip the configuration your project.

</Accordion>
</AccordionGroup>

</TabItem>
</Tabs>

## Choose Mediated Networks
<Warning>
CAS.AI is a mediation SDK with no built-in live ad inventory. At least one ad network adapter or solution must be integrated before publishing to display ads and generate revenue.
</Warning>

Choose an integration path based on your app's target audience. If you're unsure which solution best fits your application, please contact your account manager.

<Info>
During development, you can test ad formats using [Test Ads](kmp/enabling-test-ads) without adding any ad network SDKs.
</Info>

Check the details of the ad network adapters supported by CAS.AI Mediation in the [Android repository](https://github.com/cleveradssolutions/CAS-Android/blob/master/Adapters/README.md) and [iOS repository](https://github.com/cleveradssolutions/CAS-iOS/blob/master/Adapters/README.md) tables.

### Android
The CAS Gradle plugin offers curated solutions that CAS.AI keeps up to date.

<AccordionGroup>
<Accordion defaultOpen title="Optimal Ads Solution">

Recommended for **most applications** targeting a **general or mixed audience**. Includes a broad set of stable, high-performance networks.

```kotlin
// <project>/shared/build.gradle.kts
cas {
    includeOptimalAds = true
}
```

</Accordion>

<Accordion title="Families Ads Solution">

Required for applications **directed exclusively at children**, in accordance with the [Google Play Families Policy](https://support.google.com/googleplay/android-developer/answer/12918983?hl=en) and fully compatible with the [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy).

```kotlin
// <project>/shared/build.gradle.kts
cas {
    includeFamiliesAds = true
}
```

</Accordion>

<Accordion title="VPN Compliant Ads Solutions">

Designed specifically for applications that provide VPN or proxy services. This solution includes partner networks that comply with VPN-related traffic policies and restrictions.

```kotlin
// <project>/shared/build.gradle.kts
cas {
    includeVPNCompliantAds = true
}
```

</Accordion>

<Accordion title="Choice mediation adapters">

Advanced publishers familiar with ad network integrations can configure their own set of adapters.

```kotlin
// <project>/shared/build.gradle.kts
cas {
    adapters {
        googleAds = true
        unityAds = true
        appLovin = true
    }
}
```

For detailed instructions on how to integrate specific adapters into your app, refer to the [Android page](android/mediated-networks).

</Accordion>
</AccordionGroup>

### iOS
The Swift Package exposes a curated solution product that pulls a whole set of networks at once, and one
library product per network for a hand-picked set. Adding a network is an Xcode step, not a code change: the
product carries the adapter binary and the CAS.AI SDK picks it up at runtime.

<AccordionGroup>
<Accordion defaultOpen title="Optimal Ads Solution">

Recommended for **most applications** targeting a **general or mixed audience**. Includes a broad set of stable, high-performance networks.

Add the `AdsOptimalSolutions` product to your application target.

> Networks included: Google Ads, Unity Ads, IronSource, Liftoff Monetize, InMobi, Mintegral, AppLovin, Pangle, Bigo, Yango Ads, Audience Network, YSO Network, CAS Exchange, Maticoo.

</Accordion>

<Accordion title="Families Ads Solution">

Required for applications **directed exclusively at children**, in accordance with the [Google Play Families Policy](https://support.google.com/googleplay/android-developer/answer/12918983?hl=en) and fully compatible with the [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy).

Add the `AdsFamiliesSolutions` product to your application target.

> Networks included: Google Ads, Unity Ads, IronSource, Liftoff Monetize, InMobi, Chartboost, Kidoz, Mintegral, Yango Ads.

</Accordion>

<Accordion title="VPN Compliant Ads Solutions">

Designed specifically for applications that provide VPN or proxy services. This solution includes partner networks that comply with VPN-related traffic policies and restrictions.

Add the `AdsVPNCompliantSolutions` product to your application target.

> Networks included: Google Ads, Unity Ads, IronSource, Liftoff Monetize, InMobi, Mintegral, Bigo, Yango Ads, YSO Network, Monetrix.

</Accordion>

<Accordion title="Choice mediation adapters">

Advanced publishers familiar with ad network integrations can configure their own set of adapters.

Add the `CleverAdsSolutionsSPM` product, which is the CAS.AI SDK itself, and one `CASMediation*` product per
network you want to monetize with.

The library product of a network is its name in the
[adapters table of the CAS iOS repository](https://github.com/cleveradssolutions/CAS-iOS/blob/master/Adapters/README.md)
prefixed with `CASMediation`, for example `CASMediationGoogleAds` for the `GoogleAds` row. The one exception
is `CASExchange`, whose product is `CASMediationExchange`. Xcode lists the exact products when you add the
package, so you never have to guess.

The **SPM** column of that table says whether the adapter is distributed through Swift Package Manager. A few
are not, because of limitations of the ad frameworks themselves. If you need one of those, use the
[CocoaPods integration](ios) instead.

</Accordion>
</AccordionGroup>

<Info>
The solution products arrived in CAS `4.8.3`. On an earlier version of the package, add the `CASMediation*`
products of a solution one by one.
</Info>

#### Add the products to your target

<Tabs groupId="iosnetworks">
<TabItem label="In Xcode" value="xcode">
If you are adding the package for the first time, tick the products in the dialog that Xcode shows after
**Add Package**.

To change the selection later:
1. Select your project in the Project navigator, then select the application target.
2. Open the **General** tab and find **Frameworks, Libraries, and Embedded Content**.
3. Click **+**, pick the products you want from the `CleverAdsSolutions` package, and confirm.
4. Remove a product from the same list to drop a network.
</TabItem>
<TabItem label="In Package.swift" value="manifest">
If your Xcode project consumes a local Swift package of your own, list the products as dependencies of your target:

```swift
.target(
    name: "YourApp",
    dependencies: [
        // A curated solution brings the CAS.AI SDK and its networks with it.
        .product(name: "AdsOptimalSolutions", package: "CleverAdsSolutions"),

        // Or pick the networks yourself, alongside the SDK product.
        // .product(name: "CleverAdsSolutionsSPM", package: "CleverAdsSolutions"),
        // .product(name: "CASMediationGoogleAds", package: "CleverAdsSolutions"),
        // .product(name: "CASMediationUnityAds", package: "CleverAdsSolutions"),
    ],
    linkerSettings: [
        .unsafeFlags(["-ObjC"])
    ]
)
```
</TabItem>
</Tabs>

<Warning>
The Android and iOS network sets are configured separately and are expected to differ. Not every network
ships an adapter for both platforms, store policies for child-directed apps do not approve the same networks,
and individual iOS adapters raise the minimum deployment target. Pick the networks per platform rather than
mirroring one list onto the other.
</Warning>

## Advertising Identifier
CAS Mediation uses the [Google Advertising ID](https://support.google.com/googleplay/android-developer/answer/6048248?hl=en) and [Apple Identifier for Advertisers (IDFA)](https://developer.apple.com/documentation/adsupport) to deliver personalized and more relevant ads to each user.
To enable the use of the Advertising ID in your app, you need to complete the following setup steps.

<AccordionGroup>
<Accordion title="Android Google Advertising ID">
CAS Mediation allows you to easily enable or disable the use of the Advertising ID, depending on your app’s privacy requirements.

```kotlin
// <project>/shared/build.gradle.kts
cas {
    useAdvertisingId = true
}
```

An application must not use an advertising identifier if **at least one** of the following conditions is true:
- The app’s target audience includes **only children**, as defined in the [Families Policy](https://support.google.com/googleplay/android-developer/answer/9893335?sjid=10683822576513227860-EU).
- The app is being built for **devices that do not use Google Play Services** (e.g. Amazon or Huawei devices).

</Accordion>

<Accordion title="iOS User Tracking Usage description">

To use the App Tracking Transparency authorization request for accessing the IDFA, update the `iosApp/Info.plist` to add the [NSUserTrackingUsageDescription](https://developer.apple.com/documentation/bundleresources/information_property_list/nsusertrackingusagedescription) key (Name in Xcode Property List Editor: `Privacy - Tracking Usage Description`) with a custom message describing your usage. Below is an example description text:
```xml
<key>NSUserTrackingUsageDescription</key>
<string>Your data will remain confidential and will only be used to provide you a better and personalised ad experience</string>
```

- Your data will remain confidential and will only be used to provide you a better and personalised ad experience
- Your data will be used to provide you a better and personalised ad experience
- Your data will be used to create a customized experience tailored to your interests
- Allowing tracking will enable more personalized ads for you
- We try to show ads for apps and products that will be most interesting to you based on the apps you use
- This identifier will be used to deliver personalized ads to you
- This only uses device info for more interesting and relevant ads

</Accordion>
<Accordion title="iOS Localizing Usage description (optional)">

To optimize performance and to improve the user experience, you can localize the `NSUserTrackingUsageDescription` string. Please follow the [Documentation > Xcode > Localization](https://developer.apple.com/documentation/xcode/localization) instructions to learn how to localize your app.
The table below gives you a variety of localizations that you can use at your discretion.

| Locale          | Description                            |
|-----------------|----------------------------------------------------------------------------|
| English (en)    | Your data will remain confidential and will only be used to provide you a better and personalised ad experience                               |
| German (de)     | Ihre Daten bleiben vertraulich und werden nur dazu verwendet, Ihnen ein besseres und personalisiertes Werbeerlebnis zu bieten                 |
| French (fr)     | Vos données resteront confidentielles et seront utilisées uniquement pour vous offrir une expérience publicitaire meilleure et personnalisée  |
| Spanish (es)    | Sus datos permanecerán confidenciales y solo se utilizarán para brindarle una experiencia publicitaria mejor y personalizada                  |
| Ukrainian (uk)  | Ваші дані залишатимуться конфіденційними та використовуватимуться лише для надання вам кращої та персоналізованої реклами                     |
| Russian (ru)    | Ваши данные останутся конфиденциальными и будут использоваться только для предоставления вам более качественной и персонализированной рекламы |
| Portuguese (pt) | Seus dados permanecerão confidenciais e serão usados apenas para lhe proporcionar uma experiência publicitária melhor e personalizada         |
| Japanese (ja)   | お客様のデータは機密として保持され、より優れたパーソナライズされた広告エクスペリエンスを提供するためにのみ使用されます |

</Accordion>
</AccordionGroup>
```

### CAS.AI plugin for ReactNative

Source: https://production.docs.page/docs/reactnative

```mdx

Integrating CAS SDK into an app is the first step toward displaying ads and earning revenue. 
Once you've integrated and initialized the SDK, you can choose an ad format and follow the steps to implement it.

## Prerequisites
Make sure that your app's build file uses the following values:
- For Android:
  - Minimum API level `{{ min.api }}` or higher
- For iOS:
  - Use Xcode `{{ min.xcode }}` or higher
  - Minimum Target iOS version `{{ min.ios }}` or higher

## Import CAS.AI Mobile Ads package
Include the [CAS.AI plugin for ReactNative](https://www.npmjs.com/package/react-native-cas) in your ReactNative project.

<Tabs groupId="setup">
  <TabItem label="React Native" value="react">
```shell
npm install react-native-cas
```
  </TabItem>
  <TabItem label="Expo" value="expo">
```shell
npx expo install react-native-cas
```

CAS.AI provides an Expo config plugin that automatically configures the native Android and iOS projects during the `npx expo prebuild` step.
Add the plugin to your `app.json`, `app.config.js`, or `app.config.ts` file:
```js
{
  "expo": {
    "plugins": [
        [
            "react-native-cas",
            {
                // Options
            }
        ]
    ]
  }
}
```
  </TabItem>
</Tabs>


<Card title="Subscribe" icon="github" href="https://github.com/cleveradssolutions/CAS-ReactNative/subscription">
Subscribe to receive notifications about CAS updates.
</Card>

Now in your code, you can use:
```ts
import * as CASModule from 'react-native-cas';
```

## Platform specific setup
To monetize your app using CAS.AI mediation, in addition to importing the package, you need to configure your Android and iOS projects.

### Android setup

<Tabs groupId="setup">
  <TabItem label="React Native" value="react">

The CAS Android SDK provide a Gradle Plugin to simplify and automate certain integration steps.
Our plugin will automatically add mediated network dependencies to your project, which you configure in an `cas { }` block.

In your Android app Gradle file (usually `<project>/android/app/build.gradle`), add the `com.cleveradssolutions.gradle-plugin` inside the `plugins` block.
```gradle
plugins {
  id("com.android.application") // before CAS plugin
  id("com.cleveradssolutions.gradle-plugin") version "{{ versions.android }}"
}

cas {
  // Plugin configuration
}
```

<Info>
Make sure to update the CAS Gradle plugin version whenever you update the CAS ReactNative package. The CASGradle plugin version matches the version of [the CAS Android SDK](https://github.com/cleveradssolutions/CAS-Android/releases). For detailed setup instructions, visit [the CAS Android repository](android).
</Info>

Some advertising SDKs are published in their own Maven repositories. To allow Gradle to download the required artifacts, you need to add the advertising Maven `repositories` to your Gradle file.

<AccordionGroup>
<Accordion title="Manven Ads repositories">

```gradle
repositories {
  google()  
  mavenCentral()  
  maven {  
      name = "MintegralAdsRepo"  
      url = uri("https://dl-maven-android.mintegral.com/repository/mbridge_android_sdk_oversea")  
      content { includeGroup("com.mbridge.msdk.oversea") }  
  }  
  maven {  
      name = "PangleAdsRepo"  
      url = uri("https://artifact.bytedance.com/repository/pangle")  
      content { includeGroup("com.pangle.global") }  
  }
  maven {  
      name = "ChartboostAdsRepo"  
      url = uri("https://cboost.jfrog.io/artifactory/chartboost-ads/")  
      content {
          includeGroup("com.chartboost")
          includeGroup("com.iab.omid.library")
      } 
  }
  maven {  
      name = "YSONetworkRepo"  
      url = uri("https://ysonetwork.s3.eu-west-3.amazonaws.com/sdk/android")  
      content { includeGroup("com.ysocorp") }  
  }
  maven {  
      name = "OguryAdsRepo"  
      url = uri("https://maven.ogury.co")  
      content {  
          includeGroup("co.ogury")  
          includeGroup("co.ogury.module")  
      }  
  }
  maven {  
      name = "SmaatoAdsRepo"  
      url = uri("https://s3.amazonaws.com/smaato-sdk-releases/")  
      content { 
          includeGroup("com.smaato.android.sdk") 
          includeGroup("com.verve")
      }  
  }  
  maven {
      name = "VerveAdsRepo"
      url = uri("https://verve.jfrog.io/artifactory/verve-gradle-release")
      content {
          includeGroup("net.pubnative")
          includeGroup("com.verve")
          includeGroup("com.smaato.android.sdk")
      }
  }
  maven {
      name = "SuperAwesomeRepo"
      url = uri("https://aa-sdk.s3-eu-west-1.amazonaws.com/android_repo/")
      content { includeGroup("tv.superawesome.sdk.publisher") }
  }
  maven {
      name = "PubmaticAdsRepo"
      url = uri("https://repo.pubmatic.com/artifactory/public-repos")
      content { includeGroup("com.pubmatic.sdk") }
  }
  maven {
      name = "DisplayIOAdsRepo"
      url = uri("https://maven.display.io/")
      content { includeGroup("com.brandio.ads") }
  }
}
```

</Accordion>
</AccordionGroup>

  </TabItem>
  <TabItem label="Expo" value="expo">
Expo configuration automatically sets up the CAS Gradle Plugin and CAS Mediation Maven repositories for the Android project.
  </TabItem>
</Tabs>


### iOS setup
React Native automatically adds an Xcode Build Phase to run [the Ruby script for CAS project configuration](https://github.com/cleveradssolutions/CAS-iOS/tree/master/Script%20XCodeConfig).

<Tabs groupId="setup">
  <TabItem label="React Native" value="react">
 To complete the setup, you need to add the `<key>CASAIAppIdentifier</key>` property with the `<string>CASID</string>` value to the `<project>/ios/Runner/Info.plist`.

| Key                        |    Type    | Value                                  |
| -------------------------- | :--------: | -------------------------------------- |
| Information Property List  | Dictionary |                                        |
| ▼ CASAIAppIdentifier       |   String   | CASID                                  |


The `<project>/ios/Podfile` is a specification that describes the dependencies of your iOS project. 
All CAS frameworks are hosted and distributed through their own source repository. Please add CAS source repository url to the beginning of the Podfile:
```ruby
source 'https://github.com/CocoaPods/Specs.git'
source 'https://github.com/cleveradssolutions/CAS-Specs.git'
```

Mediation dependencies should be added to the `target` block, before the `end` line.
```ruby
target 'Runner' do
    pod ...
    ...
end
```
Run `pod update` terminal command inside the `ios` directory after modifying the `Podfile`.

<Info>
Make sure to update the CAS pods version whenever you update the CAS ReactNative package. The Ads Solution pods version matches the version of [the CAS iOS SDK](https://github.com/cleveradssolutions/CAS-iOS/releases).
</Info>

  </TabItem>
  <TabItem label="Expo" value="expo">
To complete the setup, you need to add the `iosAppId` property with the `CASID` value to the Expo configuration.
```js
[
    "react-native-cas",
    {
        "iosAppId": "CASID" // [!code focus]
    }
]
```

  </TabItem>
</Tabs>

<Accordion title="What is CAS ID in iOS?">

In most cases, a CASID is the same as your app store ID.  
You can find an app store ID in the URL of your app’s Apple App Store URL. For example, the URL is `apps.apple.com/us/app/id123456789` then app store ID is `123456789`.  
 
If you haven't created an CAS account and registered an app yet, now's a great time to do so at https://cas.ai  
If you just want to experiment or test the SDK, you can skip the configuration your project.

</Accordion>

## Choice Mediated Networks
<Warning>
CAS.AI is a mediation SDK with no built-in live ad inventory. At least one ad network adapter or solution must be integrated before publishing to display ads and generate revenue.
</Warning>

Choose an integration path based on your app's target audience. If you're unsure which solution best fits your application, please contact your account manager.

<Info>
During development, you can test ad formats using [Test Ads](reactnative/enabling-test-ads) without adding any ad network SDKs.
</Info>

Check the details of the ad network adapters supported by CAS.AI Mediation in the [Android repository](https://github.com/cleveradssolutions/CAS-Android/blob/master/Adapters/README.md) and [iOS repository](https://github.com/cleveradssolutions/CAS-iOS/blob/master/Adapters/README.md) tables.

<AccordionGroup>
<Accordion defaultOpen title="Optimal Ads Solution">

Recommended for **most applications** targeting a **general or mixed audience**. Includes a broad set of stable, high-performance networks.

<Tabs groupId="setup">
  <TabItem label="React Native" value="react">
  <CodeGroup>
```kotlin
// <project>/android/app/build.gradle
cas {
    includeOptimalAds = true
}
```

```ruby
# <project>/ios/Podfile
pod 'CleverAdsSolutions-SDK/Optimal', '{{ versions.ios }}'
```
</CodeGroup>
  </TabItem>
  <TabItem label="Expo" value="expo">

```js
[
    "react-native-cas",
    {
        "includeOptimalAds": true // [!code focus]
    }
]
```
  </TabItem>
</Tabs>
</Accordion>

<Accordion title="Families Ads Solution">

Required for applications **directed exclusively at children**, in accordance with the [Google Play Families Policy](https://support.google.com/googleplay/android-developer/answer/12918983?hl=en) and fully compatible with the [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy).


<Tabs groupId="setup">
  <TabItem label="React Native" value="react">
  <CodeGroup>
```kotlin
// <project>/android/app/build.gradle
cas {
    includeFamiliesAds = true
}
```

```ruby
# <project>/ios/Podfile
pod 'CleverAdsSolutions-SDK/Families', '{{ versions.ios }}'
```
</CodeGroup>
  </TabItem>
  <TabItem label="Expo" value="expo">

```js
[
    "react-native-cas",
    {
        "includeFamiliesAds": true // [!code focus]
    }
]
```
  </TabItem>
</Tabs>
</Accordion>

<Accordion title="VPN Compliant Ads Solutions">

Designed specifically for applications that provide VPN or proxy services. This solution includes partner networks that comply with VPN-related traffic policies and restrictions.

<Tabs groupId="setup">
  <TabItem label="React Native" value="react">
  <CodeGroup>
```kotlin
// <project>/android/app/build.gradle
cas {
    includeVPNCompliantAds = true
}
```

```ruby
# <project>/ios/Podfile
pod 'CleverAdsSolutions-SDK/VPNCompliant', '{{ versions.ios }}'
```
</CodeGroup>
  </TabItem>
  <TabItem label="Expo" value="expo">

```js
[
    "react-native-cas",
    {
        "includeVPNCompliantAds": true // [!code focus]
    }
]
```
  </TabItem>
</Tabs>
</Accordion>

<Accordion title="Choice mediation adapters">

Advanced publishers familiar with ad network integrations can configure their own set of adapters.

<Tabs groupId="setup">
  <TabItem label="React Native" value="react">
 
For detailed instructions on how to integrate specific adapters into your app, refer to the [Android page](android/mediated-networks) and the [iOS page](ios/mediated-networks).

  </TabItem>
  <TabItem label="Expo" value="expo">
Set list of adapters to `androidAdapters` and `iosAdapters` property.
- For iOS, the name must match the Adapter names (first column) from the [iOS Adapters table](https://github.com/cleveradssolutions/CAS-iOS/blob/master/Adapters/README.md). 
- For Android, the name must match the Adapter names (first column) from the [Android Adapters table](https://github.com/cleveradssolutions/CAS-Android/blob/master/Adapters/README.md). 

Below, as an example, only GoogleAds, CASExchange, and DTExchange are shown.

```js
[
    "react-native-cas",
    {
        "androidAdapters": ["googleAds", "casExchange", "dtExchange"] // [!code focus]
        "iosAdapters": ["GoogleAds", "CASExchange", "DTExchange"] // [!code focus]
    }
]
```
<Info>
The same adapter names can be used for both platforms if convenient.
</Info>

  </TabItem>
</Tabs>

</Accordion>
</AccordionGroup>

## Advertising Identifier
CAS.AI Plugin uses the [Google Advertising ID](https://support.google.com/googleplay/android-developer/answer/6048248?hl=en) and [Apple Identifier for Advertisers (IDFA)](https://developer.apple.com/documentation/adsupport) to deliver personalized and more relevant ads to each user.  
To enable the use of the Advertising ID in your app, you need to complete the following setup steps.

<Tabs groupId="setup">
  <TabItem label="React Native" value="react">

<AccordionGroup>
<Accordion title="Android Google Adverision ID">
CAS.AI Plugin allows you to easily enable or disable the use of the Advertising ID, depending on your app’s privacy requirements.

```kotlin
cas {
    useAdvertisingId = true // [!code focus]
}
```

An application must not use an advertising identifier if **at least one** of the following conditions is true:
- The app’s target audience includes **only children**, as defined in the [Families Policy](https://support.google.com/googleplay/android-developer/answer/9893335?sjid=10683822576513227860-EU).
- The app is being built for **devices that do not use Google Play Services** (e.g. Amazon or Huawei devices).

</Accordion>

<Accordion title="iOS User Tracking Usage description">

To use the App Tracking Transparency authorization request for accessing the IDFA, update your `<project>/ios/Runner/Info.plist` to add the [NSUserTrackingUsageDescription](https://developer.apple.com/documentation/bundleresources/information_property_list/nsusertrackingusagedescription) key (Name in Xcode Property List Editor: `Privacy - Tracking Usage Description`) with a custom message describing your usage. Below is an example description text:
```xml
<key>NSUserTrackingUsageDescription</key>
<string>Your data will remain confidential and will only be used to provide you a better and personalised ad experience</string>
```
</Accordion>
<Accordion title="iOS Localizing Usage description (optional)">

To optimize performance and to improve the user experience, you can localize the `NSUserTrackingUsageDescription` string. Please follow the [Documentation > Xcode > Localization](https://developer.apple.com/documentation/xcode/localization) instructions to learn how to localize your app.  
The table below gives you a variety of localizations that you can use at your discretion.

| Locale | Description |
|-----------------|--------------------------------------------------------------------|
| English (en)    | Your data will remain confidential and will only be used to provide you a better and personalised ad experience                               |
| German (de)     | Ihre Daten bleiben vertraulich und werden nur dazu verwendet, Ihnen ein besseres und personalisiertes Werbeerlebnis zu bieten                 |
| French (fr)     | Vos données resteront confidentielles et seront utilisées uniquement pour vous offrir une expérience publicitaire meilleure et personnalisée  |
| Spanish (es)    | Sus datos permanecerán confidenciales y solo se utilizarán para brindarle una experiencia publicitaria mejor y personalizada                  |
| Ukrainian (uk)  | Ваші дані залишатимуться конфіденційними та використовуватимуться лише для надання вам кращої та персоналізованої реклами                     |
| Russian (ru)    | Ваши данные останутся конфиденциальными и будут использоваться только для предоставления вам более качественной и персонализированной рекламы |
| Portuguese (pt) | Seus dados permanecerão confidenciais e serão usados apenas para lhe proporcionar uma experiência publicitária melhor e personalizada         |
| Japanese (ja)   | お客様のデータは機密として保持され、より優れたパーソナライズされた広告エクスペリエンスを提供するためにのみ使用されます                                                                                   |

</Accordion>
</AccordionGroup>

  </TabItem>
  <TabItem label="Expo" value="expo">
CAS.AI Plugin allows you to easily enable or disable the use of the Advertising ID, depending on your app’s privacy requirements.

```js
[
    "react-native-cas",
    {
        "useAdvertisingId": true // [!code focus]
    }
]
```

To use the iOS App Tracking Transparency authorization request for accessing the IDFA, update the [NSUserTrackingUsageDescription](https://developer.apple.com/documentation/bundleresources/information_property_list/nsusertrackingusagedescription) key with a custom message describing your usage by CAS.AI plugin config. Below is an example description text:
```js
[
    "react-native-cas",
    {
        "userTrackingUsageDescription": "Your data will remain confidential and will only be used to provide you a better and personalised ad experience" // [!code focus]
    }
]
```
  </TabItem>
</Tabs>

<AccordionGroup>
<Accordion title="iOS User Tracking Usage description examples">

- Your data will remain confidential and will only be used to provide you a better and personalised ad experience
- Your data will be used to provide you a better and personalised ad experience
- Your data will be used to create a customized experience tailored to your interests
- Allowing tracking will enable more personalized ads for you
- We try to show ads for apps and products that will be most interesting to you based on the apps you use
- This identifier will be used to deliver personalized ads to you
- This only uses device info for more interesting and relevant ads

</Accordion>
</AccordionGroup>
```

### CAS.AI plugin for Unity

Source: https://production.docs.page/docs/unity

```mdx

Integrating CAS SDK into an app is the first step toward displaying ads and earning revenue. 
Once you've integrated and initialized the SDK, you can choose an ad format and follow the steps to implement it.

## Prerequisites
- Use Unity Editor 2021.3+ or higer.
- For Android:
  - Minimum API level `{{ min.api }}` or higher.  
    Unity Editor versions below 6 may require a minimum API level of `24` for a successful build.
- For iOS:
  - Use Xcode `{{ min.xcode }}` or higher
  - Minimum Target iOS version `{{ min.ios }}` or higher

## Add the CAS package to Your Project
Choose one of the following methods to import the CAS Unity plugin into your Unity project.
1. OpenUPM-CLI
2. OpenUPM
3. Add package from git URL
4. Import .unitypackage

<Card title="Subscribe" icon="github" href="https://github.com/cleveradssolutions/CAS-Unity/subscription">
Subscribe to receive notifications about CAS updates.
</Card>

### (Option 1) OpenUPM-CLI
If you have the [OpenUPM CLI](https://github.com/openupm/openupm-cli#installation) installed, you can install the OpenUPM registry with the following command:
```
openupm add com.cleversolutions.ads.unity
```

### (Option 2) OpenUPM
1. Open the [package manager settings](https://docs.unity3d.com/Manual/class-PackageManager.html) by selecting the Unity menu option **Edit > Project Settings > Package Manager**.
2. Add OpenUPM as a scoped registry to the Package Manager window:
```
Name: OpenUPM
URL: https://package.openupm.com
Scopes: com.cleversolutions
```
3. Open the [package manager menu](https://docs.unity3d.com/Manual/upm-ui-install.html) by selecting the Unity menu option **Window > Package Manager**.
4. Set the manager scope drop-down to select **My Registries**.

![image](https://docs.unity3d.com/uploads/Main/upm-ui-unityregistry.png)

5. Select the **CleverAdsSolutions** package from the package list.
6. Press **Install**.

### (Option 3) Add package from git URL
In your open Unity project, navigate to `Window -> Package Manager -> + -> Add package from Git URL` and add url:   

1. Open the [package manager menu](https://docs.unity3d.com/Manual/upm-ui-install.html) by selecting the Unity menu option **Window > Package Manager**.
2. Press the **plus (+)** drop-down to select **Add package from Git URL**.

![image](https://user-images.githubusercontent.com/22005013/135641554-c38422fa-995e-4e56-9c3a-a89a72172081.png)

3. Enter the CAS Git URL in the text box and click **Add**:
```
https://github.com/cleveradssolutions/CAS-Unity.git#{{ versions.unity }}
```
The CAS Git URL end with the tag name after `#`.

<Info>
Check Prerequisites and Troubleshooting on [Install a package from a Git URL](https://docs.unity3d.com/Manual/upm-ui-giturl.html) page of Unity Documentation.  
</Info>

### (Option 4) Import `.unitypackage`
1. Download latest [CleverAdsSolutions.unitypackage](https://github.com/cleveradssolutions/CAS-Unity/releases/latest)
2. In your open Unity project, navigate to `Assets > Import Package > Custom Package`.
3. In the `Import Unity Package` window, make sure all of the files are selected and click **Import**.

### Remove `.unitypackage` plugin assets
If you are migrating from using a `.unitypackage` to using OpenUPM, you must manually uninstall the assets from the old location. Remove the following directories that were imported from the `.unitypackage`:
- `Assets/CleverAdsSolutions`

## Add the External Dependency Manager for Unity  
The CAS Unity plugin is distributed with the [External Dependency Manager for Unity](https://github.com/googlesamples/unity-jar-resolver#external-dependency-manager-for-unity) library. This library is intended for use by any Unity plugin that requires access to Android specific libraries (e.g., AARs) or iOS CocoaPods. It provides Unity plugins the ability to declare dependencies, which are then automatically resolved and copied into your Unity project.
1. Download latest [external-dependency-manager.unitypackage](https://github.com/googlesamples/unity-jar-resolver/blob/master/external-dependency-manager-latest.unitypackage).
2. In your open Unity project, navigate to `Assets > Import Package > Custom Package`.
3. In the `Import Unity Package` window, make sure all of the files are selected and click **Import**.
```

### CAS.AI plugin for Unreal

Source: https://production.docs.page/docs/unreal

```mdx

Integrating CAS SDK into an app is the first step toward displaying ads and earning revenue. 
Once you've integrated and initialized the SDK, you can choose an ad format and follow the steps to implement it.

## Prerequisites
- For Android:
  - Minimum API level `{{ min.api }}` or higher. 
- For iOS:
  - Use Xcode `{{ min.xcode }}` or higher
  - Minimum Target iOS version `{{ min.ios }}` or higher


## Add the Plugin to Your Project
1. Open Project root directory.
2. Create `Plugins` folder at the same level as the standard `Source` folder.
3. Download latest [Source code(zip)](https://github.com/cleveradssolutions/CAS-Unreal/releases/latest) and unpack archive to the `Plugins` directory.  
  You can also simply clone the git plugin repository into the Plugins directory.

You can also find precompiled (with binaries) CAS.AI plugin packages in the list of assets attached to the GitHub release. Please note that these packages are built only for specific versions of Unreal Engine and cannot be used with other versions.

<Card title="Subscribe" icon="github" href="https://github.com/cleveradssolutions/CAS-Unreal/subscription">
Subscribe to receive notifications about CAS updates.
</Card>

Check your project structure after adding the `uplugin`:
```md
UnrealProjectRoot
├── Content
├── Plugins
│   ├── CAS-Unreal
│   │   ├── CleverAdsSolutions.uplugin
├── Source
```

## Import the Plugin into Unreal
To use the CAS Unreal Plugin from C++ scripts, you need add `CleverAdsSolutions` module as a dependency to the `PublicDependencyModuleNames` array inside of your app’s `<PROJECTNAME>.Build.cs` file:
```csharp
PublicDependencyModuleNames.Add("CleverAdsSolutions");
```

<Image width="671" alt="image" src="/assets/unreal/index-1.png" />

## Project structure for Windows machine
When building an application on a Windows machine, it is crucial to ensure that your project folder is located on the same drive as the Unreal Engine installation directory. (e.g., both on `C:` or both on `D:`)  
Unreal Engine relies on specific paths and directories during the build process. If the project and Unreal Engine are located on different drives, it may cause path resolution problems, leading to potential build failures or incorrect behavior.
```

### Ad errors

Source: https://production.docs.page/docs/android/ad-errors

```mdx

In cases where an ad fails to load/show, a callback is called which provides a `AdError` object.

AdError is commonly used in ad-related callbacks such as `onAdFailedToLoad` or `onAdFailedToShow`.

This ad error object has the following methods:
- `int getCode()`  
    Returns the unique `AdErrorCode` that identifies the type of error. 
    Use to programmatically handle specific error cases.
- `String getMessage()`  
    Returns a human-readable message describing the error.  
    Use for for logging or debugging purposes.


### AdErrorCode constants
All errors are divided into the following categories defined in `AdErrorCode`.

| Code | Constant            | Description                                                                                                                                                                                            |
| ---- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 0    | INTERNAL_ERROR      | Indicates an internal error occurred.                                                                                                                                                                  |
| 1    | NOT_READY           | Indicates that ads are not ready to be shown. Ensure to call the appropriate ad loading method or use automatic load mode. If using automatic load mode, wait a little longer for ads to be ready.     |
| 2    | REJECTED            | Indicates that the device is rejected for services. Services may not be available for some devices that do not meet the requirements. For example, the country or version of the OS.                   |
| 3    | NO_FILL             | Indicates that no ads are available to be served. If ads are visible in test ads mode, your implementation is correct, and ads will be served once live.                                               |
| 6    | REACHED_CAP         | Indicates that the ad creative has reached its daily cap for the user. This is typically relevant for cross-promotion ads only.                                                                        |
| 7    | NOT_INITIALIZED     | Indicates that the CAS Mediation is not initialized. Ensure to add SDK initialization code in your Application's `onCreate` function.                                                                  |
| 8    | TIMEOUT             | Indicates a timeout error occurred because the advertising source did not respond in time. The system will continue waiting for a response, which may delay ad loading or cause a loading error.       |
| 9    | NO_CONNECTION       | Indicates that there is no internet connection available, which prevents ads from loading.                                                                                                             |
| 10   | CONFIGURATION_ERROR | Indicates that there is a configuration error in one of the mediation ad sources. Report this error to your support manager for further assistance.                                                    |
| 11   | NOT_PASSED_INTERVAL | Indicates that the interval between impressions of interstitial ads has not yet passed. This error may also occur if a trial ad-free interval has been defined and has not yet passed since app start. |
| 12   | ALREADY_DISPLAYED   | Indicates that another fullscreen ad is currently being displayed, preventing new ads from showing. Review your ad display logic to avoid duplicate impressions.                                       |
| 13   | NOT_FOREGROUND      | Indicates that ads cannot be shown because the application is not currently in the foreground.                                                                                                         |
```

### Additional Meta AudienceNetwork steps

Source: https://production.docs.page/docs/android/additional-meta-audiencenetwork-steps

```mdx

## Data Processing Options for US Users
Meta Audience Network Data Processing Options for US Users Limited Data Use is a data processing option that gives you more control over how your data is used in Meta’s systems and better supports your compliance efforts with various US state privacy regulations. To utilize this feature, you must proactively enable Limited Data Use.  
Visit [Meta’s developer documentation](https://developers.facebook.com/docs/marketing-apis/data-processing-options) for details.

Import `AdSettings` from Audience Network library:

<CodeGroup synchronize={true}>
```kotlin
import com.facebook.ads.AdSettings
```

```java
import com.facebook.ads.AdSettings;
```
</CodeGroup>

If you do not want to enable Limited Data Use (LDU) mode, pass an empty string array: 

<CodeGroup synchronize={true}>
```kotlin
AdSettings.setDataProcessingOptions(arrayOf())
```

```java
AdSettings.setDataProcessingOptions(new String[] {});
```
</CodeGroup>

To enable LDU for users and specify user geography, call `setDataProcessingOptions` in a form like this: 

<CodeGroup synchronize={true}>
```kotlin
AdSettings.setDataProcessingOptions(arrayOf("LDU"))
```

```java
AdSettings.setDataProcessingOptions(new String[] {"LDU"});
```
</CodeGroup>

You can determine whether the user has consented to Meta or not with Additional Consent from CMP. To do so, use code like the following: 

<CodeGroup synchronize={true}>
```kotlin
import com.cleversolutions.ads.ConsentStatus
import com.cleversolutions.ads.android.CAS
import com.facebook.ads.AdSettings

val metaConsent: Int = CAS.settings.getAdditionalConsent(89)
when (metaConsent) {
    ConsentStatus.ACCEPTED -> {
        AdSettings.setDataProcessingOptions(arrayOf())
    }
    ConsentStatus.DENIED -> {
        AdSettings.setDataProcessingOptions(arrayOf("LDU"))
    }
    else -> {
        // AC String is not available on disk.
        // Please check for consent status after the user completes the CMP flow.
    }
}
```

```java
import com.cleversolutions.ads.ConsentStatus;
import com.cleversolutions.ads.android.CAS;
import com.facebook.ads.AdSettings;

int metaConsent = CAS.settings.getAdditionalConsent(89);
if (metaConsent == ConsentStatus.ACCEPTED) {
    AdSettings.setDataProcessingOptions(new String[] {});
} else if (metaConsent == ConsentStatus.DENIED) {
    AdSettings.setDataProcessingOptions(new String[] {"LDU"});
} else {
    // AC String is not available on disk. 
    // Please check for consent status after the user completes the CMP flow.
}
```
</CodeGroup>
```

### Additional Yandex Mobile Ads steps

Source: https://production.docs.page/docs/android/additional-yandex-mobile-ads-steps

```mdx

Yandex App Metrics will be added along with Yandex Ads SDK.

<Warning>
You should take into account some features of the AppMetrica library during initialization.   
For more information, see [Features of the AppMetrica library](https://yandex.ru/support2/appmetrica-io/ru/sdk/android/analytics/android-features).   
</Warning>

<Warning> 
The code in the `Application.onCreate()` method runs multiple times for each processes.
</Warning>
 
If you encounter an initialization error after integrating a third-party library, make sure that the third-party library is initialized only in the main process.  

<Info> 
The CAS SDK automatically initializes the Yandex Mobile Ads SDK, and the Yandex Mobile Ads SDK activates AppMetrica for its operation. Additionally, the CAS SDK automatically initializes Firebase Analytics for collecting ad_impression events.  
When the CAS SDK initializes the Yandex Mobile Ads SDK before initializing Firebase Analytics, it leads to a crash in the app.
</Info>

When using Firebase Performance Monitoring in Firebase version 31.0.0+, activate FirebaseApp for all processes, including the AppMetrica SDK process. In `Application#onCreate()`, call `FirebaseApp.initializeApp(this)` before activating the AppMetrica SDK. Otherwise, the AppMetrica SDK won't be activated.

<CodeGroup synchronize={true}>
```kotlin
class YourApplication : Application() {

    override fun onCreate() {
        super.onCreate()

        // if app use FirebaseApp then init it first for all processes
        FirebaseApp.initializeApp(this)

        // if app use AppMetrica then activate it for all processes
        val config = AppMetricaConfig.newConfigBuilder(API_KEY).build()
        AppMetrica.activate(this, config)

        if (CASUtilities.isMainProcess(this)) {
            // Before user finishes the consent flow

            // Initializing third-party SDKs for main process only

            // Initialize CAS
            CAS.buildManager()
                .withCompletionListener { initConfig ->
                    // After the user finishes the consent flow

                    // Initializing third-party SDKs for all processes

                    if (CASUtilities.isMainProcess(this)) {
                        // Initializing third-party SDKs for main process only
                    }
                }
                .initialize()
        }
    }
}
```

```java
class YourApplication extends Application { 

    @Override 
    public void onCreate() { 
        super.onCreate(); 
        
        // if app use FirebaseApp then init it first for all processes
        FirebaseApp.initializeApp(this);

        // if app use AppMetrica then activate it for all processes
        AppMetricaConfig config = AppMetricaConfig.newConfigBuilder(API_KEY).build(); 
        AppMetrica.activate(this, config);

        if (CASUtilities.isMainProcess(this)) { 
            // Before user finishes the consent flow 
            
            // Initializing third-party SDKs for main process only 

            // Initialize CAS 
            CAS.buildManager()
               .withCompletionListener(initConfig -> {
                  // After the user finishes the consent flow
                
                  // Initializing third-party SDKs for all processes 
                
                  if (CASUtilities.isMainProcess(this)) {
                      // Initializing thrid-party SDKs for main process only
                  }
               })
               .initialize();
        }
    } 
}
```
</CodeGroup>

<Success>
- Se also [AppMetrica Error descriptions](https://yandex.ru/support2/appmetrica-io/en/sdk/android/analytics/android-errors) on developer docs.
- Read more about [CAS initialization](android/initialize-cas).
</Success>

### Excluding geo from the list of dependencies
If you need to disable geo, for example, for certain app categories to meet Google Play policies, read how [exclude location dependencies](https://yandex.ru/support2/appmetrica-io/en/sdk/android/geo-exclude) on AppMetrica developer docs.
```

### App Open Ads

Source: https://production.docs.page/docs/android/app-open-ads

```mdx

App open ads are a special ad format intended for publishers wishing to monetize their app load screens. 
App open ads can be closed at any time, and are designed to be shown when your users bring your app to the foreground.
App open ads automatically show a small branding area so users know they're in your app.  


Below is a diagram showing the ad lifecycle.
<Image zoom src="/assets/Lifecycle-Screen-Ad.png" alt="Diagram" height="500" />


## Create Ad instance
Ad instance can be initialized along with the activity before `onCreate`.

<CodeGroup synchronize={true}>
```kotlin
import com.cleveradssolutions.sdk.screen.CASAppOpen

class MyActivity : Activity() {

    private val appOpenAd = CASAppOpen(MyApplication.CAS_ID)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ...
    }
}
```

```java
import com.cleveradssolutions.sdk.screen.CASAppOpen;

class MyActivity extends Activity {

    final CASAppOpen appOpenAd = new CASAppOpen(MyApplication.CAS_ID);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ...
    }
}
```
</CodeGroup>

The SDK provides the capability to create and precache multiple ad instances, enabling uninterrupted sequential ad display. CAS SDK will load mediation ads in order for each created instance.

## Create Ad Content callback

The `com.cleveradssolutions.sdk.screen.ScreenAdContentCallback` handles events related to displaying your `CASAppOpen`. Callbacks are called on the main thread. Before showing ad, make sure to `setContentCallback()`.

<CodeGroup synchronize={true}>
```kotlin
val adContentCallback = object : ScreenAdContentCallback {
    override fun onAdLoaded(ad: AdContentInfo) {
        // (Optional) Called when the ad content has been successfully loaded.
    }

    override fun onAdFailedToLoad(format: AdFormat, error: AdError) {
        // (Optional) Called when the ad content fails to load.
    }

    override fun onAdFailedToShow(format: AdFormat, error: AdError) {
        // (Optional) Called when the ad content fails to show.
    }

    override fun onAdShowed(ad: AdContentInfo) {
        // (Optional) Called when the ad content is successfully shown.
    }

    override fun onAdClicked(ad: AdContentInfo) {
        // (Optional) Called when the ad content is clicked by the user.
    }

    override fun onAdDismissed(ad: AdContentInfo) {
        // (Optional) Called when the ad content is dismissed.
    }
}
```

```java
final ScreenAdContentCallback adContentCallback = new ScreenAdContentCallback() {  
    @Override  
    public void onAdLoaded(@NonNull AdContentInfo ad) {  
        // (Optional) Called when the ad content has been successfully loaded.  
    }  
  
    @Override  
    public void onAdFailedToLoad(@NonNull AdFormat format, @NonNull AdError error) {  
        // (Optional) Called when the ad content fails to load.  
    }  
  
    @Override  
    public void onAdFailedToShow(@NonNull AdFormat format, @NonNull AdError error) {  
        // (Optional) Called when the ad content fails to show.  
    }  
  
    @Override  
    public void onAdShowed(@NonNull AdContentInfo ad) {  
        // (Optional) Called when the ad content is successfully shown.  
    }  
  
    @Override  
    public void onAdClicked(@NonNull AdContentInfo ad) {  
        // (Optional) Called when the ad content is clicked by the user.  
    }  
  
    @Override  
    public void onAdDismissed(@NonNull AdContentInfo ad) {  
        // (Optional) Called when the ad content is dismissed.  
    }  
};
```
</CodeGroup>

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](android/impression-level-data).
- Attempting to load a new ad from the `onAdFailedToLoad()` method is strongly discouraged. Limit ad load retries to avoid continuous failed ad requests in situations such as limited network connectivity.
- When an error occurs during ad impression, executed the `onAdFailedToShow` only.  In this case the `onAdDismissed` will not be executed, since the impression is not considered successful.
</Info>

## Load Ad

The next step is to fill out the `load()` method and handle the ad load callbacks. 

<CodeGroup synchronize={true}>
```kotlin
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    appOpenAd.contentCallback = adContentCallback
    appOpenAd.load(this)
}
```

```java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    appOpenAd.setContentCallback(adContentCallback);
    appOpenAd.load(this);
}
```

</CodeGroup>

### Autoload mode

If enabled, the ad will automatically load new content when the current ad is dismissed or completed. Additionally, it will automatically retry loading the ad if an error occurs during the loading process.

<CodeGroup synchronize={true}>
```kotlin
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    appOpenAd.contentCallback = adContentCallback
    appOpenAd.isAutoloadEnabled = true
}

```
```java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    appOpenAd.setContentCallback(adContentCallback);
    appOpenAd.setAutoloadEnabled(true);
}
```

</CodeGroup>
By default autoload disabled.

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements.

The placement name should be set before showing the ads. Maximum 100 characters allowed for the placement name.

<CodeGroup synchronize="true">
```kotlin
appOpenAd.placement = "BestPlace"
```

```java
appOpenAd.setPlacement("BestPlace")
```
</CodeGroup>

## Show Ad

The most common app open implementation is to attempt to show an app open ad near app launch, start app content if the ad isn't ready, and preload another ad for the next app open opportunity.

<CodeGroup synchronize={true}>
```kotlin
override fun onResume() {
    super.onResume()

    if (appOpenAd.isLoaded) {      
        appOpenAd.show(this)       
    } else if (appOpenAd.isAutoloadEnabled == false) {
        appOpenAd.load(this)
    }
}
```

```java
@Override  
protected void onResume() {  
    super.onResume();  
  
    if (appOpenAd.isLoaded()) {  
        appOpenAd.show(this);  
    } else if (appOpenAd.isAutoloadEnabled() == false) {  
        appOpenAd.load(this);  
    } 
}
```
</CodeGroup>

Starting with CAS SDK version 4.3.0, all ads functions can be safely called from any thread.

Once you’ve successfully call `show()`, you will have shown your user an App Open Ad.
In the case you want to serve another App Open Ad, you must repeat `load()` to request an additional ad.

<Info>
If a user returns to your app after having left it by clicking on an app open ad, it makes sure they're not presented with another app open ad.
</Info>

### Autoshow mode

Use the `isAutoshowEnabled` property to automatically show a loaded ad when the user returns to the app. 

<CodeGroup synchronize={true}>
```kotlin
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    ...
    appOpenAd.isAutoshowEnabled = true
}
```

```java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ...
    appOpenAd.setAutoshowEnabled(true);
}
```

</CodeGroup>
By default autoshow disabled.

### Checking Ad Availability

Use `isLoaded()` to check whether an ad is currently loaded. 
<CodeGroup synchronize={true}>

```kotlin
if (appOpenAd.isLoaded) {
}
```

```java
if (appOpenAd.isLoaded()) {
}
```
</CodeGroup>

Even if `isLoaded()` returns `true`, it does not guarantee that the ad will be shown successfully — various issues may still prevent it from being displayed. We strongly recommend handling potential display failures via `onAdFailedToShow(error)` callback to ensure a smoother user experience.

By relying on these callbacks, you ensure that your application can react appropriately to real-time conditions, rather than making assumptions based on ad load state at a single point in time.

## Release ad resource

It is important to `destroy()` loaded but not displayed ads. 

<CodeGroup synchronize={true}>
```kotlin
override fun onDestroy() {
    appOpenAd.destroy()
    super.onDestroy()
}
```

```java
@Override  
protected void onDestroy() {  
    appOpenAd.destroy();  
    super.onDestroy();  
}
```
</CodeGroup>

## Cold starts and loading screens

The documentation thus far assumes that you only show app open ads when users foreground your app when it is suspended in memory. "Cold starts" occur when your app is launched but was not previously suspended in memory.

An example of a cold start is when a user opens your app for the first time. With cold starts, you won't have a previously loaded app open ad that's ready to be shown right away. The delay between when you request an ad and receive an ad back can create a situation where users are able to briefly use your app before being surprised by an out of context ad. This should be avoided because it is a bad user experience.

The preferred way to use app open ads on cold starts is to use a loading screen to load your game or app assets, and to only show the ad from the loading screen. If your app has completed loading and has sent the user to the main content of your app, do not show the ad.

<Info>
In order to continue loading app assets while the app open ad is being displayed, always load assets in a background thread.
</Info>

## Best practices

App open ads help you monetize your app's loading screen, when the app first launches and during app switches, but it's important to keep best practices in mind so that your users enjoy using your app. It's best to:

* Show your first app open ad after your users have used your app a few times.
* Show app open ads during times when your users would otherwise be waiting for your app to load.
* If you have a loading screen under the app open ad, and your loading screen completes loading before the ad is dismissed, you may want to dismiss your loading screen in the `onAdDismissed()` and `onAdFailedToShow()` methods.

## Samples
- [Kotlin AppOpen Ad Activity](https://github.com/cleveradssolutions/CAS-Android/blob/master/kotlinSample/src/main/java/com/cleveradssolutions/sampleapp/appopen/AppOpenAdActivity.kt)
- [Java AppOpen Ad Activity](https://github.com/cleveradssolutions/CAS-Android/blob/master/javaSample/src/main/java/com/cleveradssolutions/sampleapp/appopen/AppOpenAdActivity.java)
```

### Banner Ads

Source: https://production.docs.page/docs/android/banner-ads

```mdx

Banner Ad units display rectangular ads that occupy a portion of an app's layout.
They can refresh automatically after a set period of time.
This means users view a new ad at regular intervals, even if they stay on the same screen in your app.
They're also the simplest ad format to implement.

Banner ads are displayed in `CASBannerView` objects, so the first step toward integrating banner ads is to include a `CASBannerView` in your view hierarchy.
This is typically done either with the layout or programmatically.

Below is a diagram showing the ad lifecycle. <Image zoom src="/assets/Lifecycle-Banner-Ad.png" alt="Diagram" height="500" />

## Get the Ad size

To load a banner ad, you need to specify the ad size. To do this, choose one of the methods for obtaining an `AdSize` from the list below:

1. **Adaptive banner** ads have a fixed aspect ratio for the maximum width. The adaptive size calculates the optimal height for that width with an aspect ratio similar to 320x50.

<CodeGroup synchronize={true}>
```kotlin
val maxWidth = 360
val adSize = AdSize.getAdaptiveBanner(maxWidth)
```

```java
int maxWidth = 360;
AdSize adSize = AdSize.getAdaptiveBanner(maxWidth);
```

</CodeGroup>

2. **Inline banner** ads have a desired width and a maximum height, useful when you want to limit the banner's height. Inline banners are larger and taller compared to adaptive banners. They have variable height, including Medium Rectangle size, and can be as tall as the device screen.

<CodeGroup synchronize={true}>
```kotlin
val maxWidth = 360
val maxHeight = 400
val adSize = AdSize.getInlineBanner(maxWidth, maxHeight)
```

```java
int maxWidth = 360;
int maxHeight = 400;
AdSize adSize = AdSize.getInlineBanner(maxWidth, maxHeight);
```

</CodeGroup>

3. **Smart ad size** selects the optimal dimensions depending on the device type. For mobile devices, it returns 320x50, while for tablets, it returns 728x90. In the UI, these banners occupy the same amount of space regardless of device type.

<CodeGroup synchronize={true}>
```kotlin
val adSize = AdSize.getSmartBanner(context)
```

```java
AdSize adSize = AdSize.getSmartBanner(context);
```

</CodeGroup>

4. **Medium Rectangle** has a fixed size of 300x250.

<CodeGroup synchronize={true}>
```kotlin
val adSize = AdSize.MEDIUM_RECTANGLE
```

```java
AdSize adSize = AdSize.MEDIUM_RECTANGLE;
```

</CodeGroup>

5. **Leaderboard** has a fixed size of 728x90 and is allowed on tablets only.

<CodeGroup synchronize={true}>
```kotlin
val adSize = AdSize.LEADERBOARD
```

```java
AdSize adSize = AdSize.LEADERBOARD;
```

</CodeGroup>

6. **Standard banner** has a fixed size of 320x50 and is the minimum ad size.

<CodeGroup synchronize={true}>
```kotlin
val adSize = AdSize.BANNER
```

```java
AdSize adSize = AdSize.BANNER;
```

</CodeGroup>

## Create Ad View

The first step toward displaying a banner is to place `CASBannerView` in the layout for the Activity or Fragment in which you'd like to display it.

<Tabs>
<TabItem label="Programmatically" value="script">
Create an `CASBannerView` using the ad size to add to your app's layout:

<CodeGroup synchronize={true}>
```kotlin
import com.cleversolutions.ads.android.CASBannerView

class MyActivity : Activity() {
    private lateinit var bannerView: CASBannerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        bannerView = CASBannerView(this, MyApplication.CAS_ID)
        bannerView.size = adSize
        bannerView.isAutoloadEnabled = true

        // Replace ad container with new ad view.
        adContainerView.removeAllViews()
        adContainerView.addView(
            bannerView,
            LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
        )
    }
}
```

```java
import com.cleversolutions.ads.android.CASBannerView;

class MyActivity extends Activity {
    CASBannerView bannerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        bannerView = new CASBannerView(this, MyApplication.CAS_ID);
        bannerView.setSize(adSize); // or any AdSize from above
        bannerView.setAutoloadEnabled(true);
        
        // Replace ad container with new ad view.
        adContainerView.removeAllViews();
        adContainerView.addView(
            bannerView, 
            new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
        );
    }
}
```

</CodeGroup>

</TabItem>

<TabItem label="XML Layout" value="xml">

The easiest way to do this is to add one to the corresponding XML layout file.
Here's an example that shows an activity's `CASBannerView`:

```xml
# main_activity.xml
...
  <com.cleversolutions.ads.android.CASBannerView 
      xmlns:ads="http://schemas.android.com/apk/res-auto"
      android:id="@+id/bannerView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:gravity="center"
      ads:bannerSize="Standard320x50"/>
...
```

Note the following required attributes:
`ads:bannerSize` - Set the ad size you'd like to use.
See the banner size section below for details.

On create activity you should set CAS Id to the ad view:

<CodeGroup synchronize={true}>
```kotlin
import com.cleversolutions.ads.android.CASBannerView

class MyActivity : Activity() {
    private lateinit var bannerView: CASBannerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        bannerView = findViewById(R.id.bannerView)
        bannerView.casId = MyApplication.CAS_ID
        bannerView.isAutoloadEnabled = true
    }
}
```

```java
import com.cleversolutions.ads.android.CASBannerView;

class MyActivity extends Activity {
    CASBannerView bannerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bannerView = (CASBannerView)findViewById(R.id.bannerView);
        bannerView.setCasId(MyApplication.CAS_ID);
        bannerView.setAutoloadEnabled(true);
    }
}
```
</CodeGroup>

</TabItem>

<TabItem label="Compose" value="compose">

```kotlin
@Composable
fun BannerView(modifier: Modifier = Modifier) {
    val context = LocalContext.current
    val screenWidthDp = LocalConfiguration.current.screenWidthDp

    val bannerView = remember(screenWidthDp) {
        CASBannerView(context, MyApplication.CAS_ID).apply {
            // Adaptive banner based on current width.
            size = AdSize.getAdaptiveBanner(context, screenWidthDp) 
            isAutoloadEnabled = true

            // Add a listeners and other parameters to the banner view here.
            // adListener = ...
        }
    }

    AndroidView(
        modifier = modifier.wrapContentSize(),
        factory = { bannerView }
    )
}
```

</TabItem>
</Tabs>

## Listen Ad events

To further customize the behavior of your ad, you can hook onto a number of events in the ad's lifecycle: loading, clicking, and so on.
You can listen for these events through the `AdViewListener` interface.
To use an `AdViewListener` with Banner View, call the `setAdListener()` method before loading the banner:

<CodeGroup synchronize="true">
```kotlin
bannerView.adListener = object : AdViewListener {
    override fun onAdViewLoaded(view: CASBannerView) {
        // Invokes this callback when ad loaded and ready to present.
    }

    override fun onAdViewFailed(view: CASBannerView, error: AdError) {
        // Invokes this callback when an error occurred with the ad.
    }

    override fun onAdViewClicked(view: CASBannerView) {
        // Invokes this callback when a user clicks the ad.
    }

    override fun onAdViewPresented(view: CASBannerView, info: AdStatusHandler) {
        // Deprecated. Same as onAdImpression(AdContentInfo).
    }
}

```

```java
bannerView.setAdListener(new AdViewListener() {
    @Override
    public void onAdViewLoaded(@NonNull CASBannerView view) {
      // Invokes this callback when ad loaded and ready to present.
    }

    @Override
    public void onAdViewFailed(@NonNull CASBannerView view, @NonNull AdError error) {
      // Invokes this callback when an error occurred with the ad.
    }

    @Override
    public void onAdViewClicked(@NonNull CASBannerView view) {
      // Invokes this callback when a user clicks the ad.
    }

    @Override
    public void onAdViewPresented(@NonNull CASBannerView view, @NonNull AdStatusHandler info) {
      // Deprecated. Same as onAdImpression(AdContentInfo).
    }
});
```

</CodeGroup>

## Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements.

The placement name should be set before loading the ads. Maximum 100 characters allowed for the placement name.

<CodeGroup synchronize="true">
```kotlin
bannerView.placement = "BestPlace"
```

```java
bannerView.setPlacement("BestPlace")
```

</CodeGroup>

## Load Ad

Once the ad view is in place, the next step is to load an ad. That's done with the `loadAd()` method in the `CASBannerView`class.

<Tabs groupId="platform">
<TabItem label="Kotlin" value="kotlin">
```kotlin
bannerView.load()
```

</TabItem>
<TabItem label="Java" value="java">
```java
bannerView.load();
```

</TabItem>
<TabItem label="Compose" value="compose">
```kotlin
DisposableEffect(bannerView) {
    bannerView.load()
}
```

</TabItem>
</Tabs>

### Autoload Ad mode

If enabled, the ad will automatically load new content when the current ad is dismissed or completed. Additionally, it will automatically retry loading the ad if an error occurs during the loading process.

<CodeGroup synchronize="true">
```kotlin
bannerView.isAutoloadEnabled = false
```

```java
bannerView.setAutoloadEnabled(false);
```

</CodeGroup>

By default enabled.

### Handle Orientation Changes

When using an `AdSize` based on screen width, you should recalculate the size whenever
the device orientation changes and reload the banner ad to match the new layout.

<CodeGroup synchronize="true">
```kotlin
override fun onConfigurationChanged(newConfig: Configuration) {
    super.onConfigurationChanged(newConfig)
    bannerView.size = AdSize.getAdaptiveBanner(this, maxWidth)
    if (bannerView.isAutoloadEnabled == false) {
        bannerView.load()
    }
}
```

```java
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    bannerView.setSize(AdSize.getAdaptiveBanner(this, maxWidth)); 
    if (bannerView.isAutoloadEnabled() == false) {
        bannerView.load();
    }
}
```

</CodeGroup>

## Ad view visibility

The banner is a normal view so you can feel free to change the visibility with the following method:

<CodeGroup synchronize="true">
```kotlin
bannerView.visibility = View.GONE
```

```java
bannerView.setVisibility(View.GONE);
```

</CodeGroup>

## Ad refresh interval

The ad view’s automatic refresh interval determines how often a new ad request is generated for that ad view. You have the option to set a custom refresh interval longer than 10 seconds or to disable the Automatic refresh option for the ad view.

Change the banner automatic refresh interval using the following method:

<CodeGroup synchronize="true">
```kotlin
bannerView.refreshInterval = interval
```

```java
bannerView.setRefreshInterval(interval);
```

</CodeGroup>

We recommend using optimal automatic refresh interval 30 seconds, by default.

To disable refresh ad use following method:

<CodeGroup synchronize="true">
```kotlin
bannerView.disableAdRefresh()
```

```java
bannerView.disableAdRefresh();
```

</CodeGroup>

<Info>
- The automatic refresh occurs only if the banner is visible on screen.  
- The `isAutoloadEnabled` has no effect on refreshing the banner ad.
</Info>

## Release ad resource

Be sure to release ad resources if you’re no longer going to use the ad view.

<Tabs groupId="platform">
<TabItem label="Kotlin" value="kotlin">
```kotlin
override fun onDestroy() {
    super.onDestroy()
    bannerView.destroy()
}
```

</TabItem>
<TabItem label="Java" value="java">
```java
@Override
protected void onDestroy() {
  super.onDestroy();
  bannerView.destroy();
}
```

</TabItem>
<TabItem label="Compose" value="compose">
```kotlin
DisposableEffect(bannerView) {
    onDispose { bannerView.destroy() }
}
```

</TabItem>
</Tabs>

## Check Ad availability

Use `isLoaded()` to check whether an ad is currently loaded.

<CodeGroup synchronize="true">
```kotlin
if (bannerView.isLoaded) {
}
```

```java
if (bannerView.isLoaded()) {
}
```

</CodeGroup>

## Samples
- Kotlin samples
  - [Banner Ad Activity](https://github.com/cleveradssolutions/CAS-Android/blob/master/kotlinSample/src/main/java/com/cleveradssolutions/sampleapp/banner/programmatic/BannerAdActivity.kt)
  - [Adaptive Banner Ad Activity](https://github.com/cleveradssolutions/CAS-Android/blob/master/kotlinSample/src/main/java/com/cleveradssolutions/sampleapp/banner/xml/AdaptiveBannerAdActivity.kt)
- Java samples
  - [Banner Ad Activity](https://github.com/cleveradssolutions/CAS-Android/blob/master/javaSample/src/main/java/com/cleveradssolutions/sampleapp/banner/programmatic/BannerAdActivity.java)
  - [Adaptive Banner Ad Activity](https://github.com/cleveradssolutions/CAS-Android/blob/master/javaSample/src/main/java/com/cleveradssolutions/sampleapp/banner/xml/AdaptiveBannerAdActivity.java)
- Jetpack Compose samples
  - [Banner Screen](https://github.com/cleveradssolutions/CAS-Android/blob/master/composeSample/src/main/java/com/cleveradssolutions/sampleapp/formats/BannerScreen.kt)
  - [Lazy Banner Screen](https://github.com/cleveradssolutions/CAS-Android/blob/master/composeSample/src/main/java/com/cleveradssolutions/sampleapp/formats/LazyBannerScreen.kt)

## Hardware acceleration for video ads

In order for video ads to show successfully in your banner ad views, [hardware acceleration](https://developer.android.com/guide/topics/graphics/hardware-accel) must be enabled.

Hardware acceleration is enabled by default, but some apps may choose to disable it. If this applies to your app, we recommend enabling hardware acceleration for Activity classes that use ads.

If your app does not behave properly with hardware acceleration turned on globally, you can control it for individual activities as well. To enable or disable hardware acceleration, you can use the `android:hardwareAccelerated` attribute for the [application](https://developer.android.com/guide/topics/manifest/application-element) and [activity](https://developer.android.com/guide/topics/manifest/activity-element) elements in your **AndroidManifest.xml**. The following example enables hardware acceleration for the entire app but disables it for one activity:

```xml
<application android:hardwareAccelerated="true">
    <!-- For activities that use ads, hardwareAcceleration should be true. -->
    <activity android:hardwareAccelerated="true" />
    <!-- For activities that don't use ads, hardwareAcceleration can be false. -->
    <activity android:hardwareAccelerated="false" />
</application>
```

See the [HW acceleration](https://developer.android.com/guide/topics/graphics/hardware-accel) guide for more information about options for controlling hardware acceleration. Note that individual ad views cannot be enabled for hardware acceleration if the Activity is disabled, so the Activity itself must have hardware acceleration enabled.
```

### Display Native Ad

Source: https://production.docs.page/docs/android/display-native-ad

```mdx

For the Native Ad format, there is the corresponding `com.cleveradssolutions.sdk.nativead.CASNativeView` class. This class is a `ViewGroup` that publishers should use as the root for the `NativeAdContent`. A single `CASNativeView` corresponds to a single native ad. Each view used to display that ad's assets (the `ImageView` that displays the screenshot asset, for instance) should be a child of the `CASNativeView` object.

Here are the individual tasks:
<Steps>
<Step title="Inflate the layout">
See below how you can layout the views using Templates or Manual. 
</Step>
<Step title="Register the asset views">
See below how you can register the asset views using Templates or Manual.
Values for registered views will be set automatically when calling `bindAdContent()`.  
Note that views for which the loaded ad does not provide content will be hidden with `view.setVisibility(View.GONE)`.
See below for the implementation of `registerAdAssetViews(adView)` function.
</Step>
<Step title="Handle clicks">
Don't implement any custom click handlers on any views over or within the native ad view. To observe click events yourself, use the ad callback `onNativeAdClicked`. Clicks on the ad view assets are handled by the SDK as long as you correctly populate and register the asset views, as discussed in the previous section.
</Step>
<Step title="Register the native ad content">
This final step registers the native ad object with the view that's responsible for displaying it. Note that you can also reuse an existing `CASNativeView` if one is already present in your fragment or activity, or you can create an instance dynamically without using a layout file. Simply call `bindAdContent` for each new `NativeAdContent` as shown in `registerNativeAdContent()` function.
</Step>
</Steps>

<CodeGroup synchronize={true}>
```kotlin
lateinit var adView: CASNativeView

override fun onCreate(@Nullable savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val container = findViewById<ViewGroup>(R.id.native_ad_container)
    inflateNativeAdView(container)
    registerAdAssetViews(adView)
}

fun registerNativeAdContent(nativeAd: NativeAdContent) {
    adView.bindAdContent(nativeAd)
}
```

```java
CASNativeView adView;

@Override  
protected void onCreate(@Nullable Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ViewGroup container = (ViewGroup) findViewById(R.id.native_ad_container);
    inflateNativeAdView(container);
    registerAdAssetViews(adView);
}

void registerNativeAdContent(NativeAdContent nativeAd) {
    adView.bindAdContent(nativeAd);
}
```
</CodeGroup>

<Warning>  
The `bindAdContent(NativeAdContent)` method must be called from the main (UI) thread.
</Warning>

## Validate Ad Content (Optional)

Native ads can be preloaded and cached to reduce latency when displaying ads to users. However, these ads have a limited lifespan and may expire after a certain period. To ensure a seamless user experience, you should validate the ad content before displaying it.

Use the `NativeAdContent.isExpired` method to check if the ad has expired. If you attempt to display an expired ad, it will trigger an `onNativeAdFailedToShow` callback.

<CodeGroup synchronize={true}>
```kotlin
fun registerNativeAdContent(nativeAd: NativeAdContent) {
    if (nativeAd.isExpired) {
        loadNativeAds()
        return
    }
    adView.bindAdContent(nativeAd)
}
```

```java
void registerNativeAdContent(NativeAdContent nativeAd) {
    if (nativeAd.isExpired()) {
        loadNativeAds();
        return;
    }
    adView.bindAdContent(nativeAd);
}
```
</CodeGroup>

If you display the ad immediately in `onNativeAdLoaded`, there's no need to check its validity, as it is guaranteed to be fresh at that moment.

## Display native ad Templates

### Inflate the layout

The easiest way to integrate native ads into your app is via the templates API. You just need to create the empty `CASNativeView`, add ad view to layout and `setAdTemplateSize`.

<Tabs groupId="platform">
<TabItem label="Kotlin" value="kotlin">
```kotlin
fun inflateNativeAdView(container: ViewGroup) {
    adView = CASNativeView(this)
    val size = AdSize.MEDIUM_RECTANGLE
    adView.setAdTemplateSize(size)

    customizeAdViewAppearance(adView)

    container.addView(adView)
}
```

</TabItem>
<TabItem label="Java" value="java">
```java
void inflateNativeAdView(ViewGroup container) {
    adView = new CASNativeView(this);
    AdSize size = AdSize.MEDIUM_RECTANGLE;
    adView.setAdTemplateSize(size);

    customizeAdViewAppearance(adView);
    
    container.addView(adView);
}
```

</TabItem>
<TabItem label="Compose" value="compose">
```kotlin
@Composable
fun NativeAdTemplateView(adContent: NativeAdContent, modifier: Modifier = Modifier) {
    val context = LocalContext.current
    val screenWidthDp = LocalConfiguration.current.screenWidthDp

    // Create the native view once per width change.
    val nativeView = remember(availableWidthDp) {
        CASNativeView(context).apply {
            setAdTemplateSize(AdSize.getInlineBanner(screenWidthDp, 300))
        }
    }

    // Apply ad content to the view on the main thread
    LaunchedEffect(adContent, nativeView) {
        nativeView.bindAdContent(adContent)
    }

    // Compose android view
    AndroidView(
        modifier = modifier
            .fillMaxWidth()
            .height(300.dp),
        factory = { nativeView }
    )
}
```

</TabItem>
</Tabs>

<Info>
Creating the layout may cause UI rendering to freeze briefly, so it is recommended to set the template size only once when initializing the view.  
The `setAdTemplateSize(AdSize)` method must be called from the main (UI) thread.
</Info>

**Optional:** Customize the appearance of asset views after calling `setAdTemplateSize` by modifying properties from the `CASNativeView`.

<CodeGroup synchronize={true}>
```kotlin
fun customizeAdViewAppearance(adView: CASNativeView) {
    // Default values are shown below:
    adView.setBackgroundColor(Color.WHITE)

    adView.callToActionView?.setBackgroundResource(R.drawable.cas_rounded_button)
    adView.headlineView?.setTextColor(Color.parseColor("#80000000"))
}
```

```java
void customizeAdViewAppearance(CASNativeView adView) {
    // Default values are shown below:
    adView.setBackgroundColor(Color.WHITE);
    
    adView.getCallToActionView().setBackgroundResource(R.drawable.cas_rounded_button);
    adView.getHeadlineView().setTextColor(Color.parseColor("#80000000"));
}
```
</CodeGroup>

### Register the asset views

When you set the ad template size using `setAdTemplateSize`, the `CASNativeView` automatically registers all native asset views with the corresponding template assets for the selected size.

<CodeGroup synchronize={true}>
```kotlin
fun registerAdAssetViews(adView: CASNativeView) {
    // No manual registration is required.
}
```

```java
void registerAdAssetViews(CASNativeView adView) {
    // No manual registration is required.
}
```
</CodeGroup>

## Manual display native ad

The code below shows how to display a Native Ad View using an Android Layout.  

If you are using Jetpack Compose, it is recommended to check out the [Composable Views for Native Ad Assets](https://github.com/cleveradssolutions/CAS-Android/blob/master/composeSample/src/main/java/com/cleveradssolutions/compose/NativeAdCompose.kt) in our usage sample project.

### Inflate the layout

The view hierarchy for a native ad that uses a `LinearLayout` to display its asset views might look like this:

```xml
<com.cleveradssolutions.sdk.nativead.CASNativeView
    xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout android:orientation="vertical">
        <LinearLayout android:orientation="horizontal">
            <ImageView android:id="@+id/ad_icon" />
            <TextView android:id="@+id/ad_headline" />
            <com.cleveradssolutions.sdk.nativead.CASChoicesView
                android:id="@+id/ad_choices_view" />
        </LinearLayout>
        <com.cleveradssolutions.sdk.nativead.CASMediaView
            android:id="@+id/ad_media_view" />
        <com.cleveradssolutions.sdk.nativead.CASStarRatingView
            android:id="@+id/ad_star_rating" />

        <!-- Other assets such as image or call to action, etc follow. -->
    </LinearLayout>
</com.cleveradssolutions.sdk.nativead.CASNativeView>
```

Note that all assets for a given native ad should be rendered inside the `CASNativeView` layout.

Here is an example that inflate a `CASNativeView` and populates it with a `NativeAdContent`:

<CodeGroup synchronize={true}>
```kotlin
fun inflateNativeAdView(container: ViewGroup) {
    val attachToContainer = false // to return AdView
    val adView = LayoutInflater.from(container.context)
        .inflate(R.layout.native_ad_layout, container, attachToContainer) as CASNativeView

    container.addView(adView)
}
```

```java
void inflateNativeAdView(ViewGroup container) {
    boolean attachToContainer = false; // to return AdView
    CASNativeView adView = (CASNativeView) LayoutInflater.from(container.getContext())
        .inflate(R.layout.native_ad_layout, container, attachToContainer); 
    
    container.addView(adView);
}
```
</CodeGroup>

Assumes that your ad layout is in a file called `native_ad_layout.xml` in the `res/layout` folder.

### Register the asset views

To register the ad view with content, you need to register all the asset views that may be used.

<CodeGroup synchronize={true}>
```kotlin
fun registerAdAssetViews(adView: CASNativeView) {
    // You can also omit adChoicesView and it will be created automatically.
    adView.adChoicesView = adView.findViewById<CASChoicesView>(R.id.ad_choices_view)

    adView.mediaView = adView.findViewById<CASMediaView>(R.id.ad_media_view)
    adView.adLabelView = adView.findViewById<TextView>(R.id.ad_label)
    adView.headlineView = adView.findViewById<TextView>(R.id.ad_headline)
    adView.iconView = adView.findViewById<ImageView>(R.id.ad_icon)
    adView.callToActionView = adView.findViewById<Button>(R.id.ad_call_to_action)
    adView.bodyView = adView.findViewById<TextView>(R.id.ad_body)
    adView.advertiserView = adView.findViewById<TextView>(R.id.ad_advertiser)
    adView.storeView = adView.findViewById<TextView>(R.id.ad_store)
    adView.priceView = adView.findViewById<TextView>(R.id.ad_price)
    adView.reviewCountView = adView.findViewById<TextView>(R.id.ad_review_count)
    adView.starRatingView = adView.findViewById(R.id.ad_star_rating)
}
```

```java
void registerAdAssetViews(CASNativeView adView) {
    // You can also omit adChoicesView and it will be created automatically.
    adView.setAdChoicesView((CASChoicesView) adView.findViewById(R.id.ad_choices_view));

    adView.setMediaView((CASMediaView) adView.findViewById(R.id.ad_media_view));
    adView.setAdLabelView((TextView) adView.findViewById(R.id.ad_label));
    adView.setHeadlineView((TextView) adView.findViewById(R.id.ad_headline));
    adView.setIconView((ImageView) adView.findViewById(R.id.ad_icon));
    adView.setCallToActionView((Button) adView.findViewById(R.id.ad_call_to_action));
    adView.setBodyView((TextView) adView.findViewById(R.id.ad_body));
    adView.setAdvertiserView((TextView) adView.findViewById(R.id.ad_advertiser));
    adView.setStoreView((TextView) adView.findViewById(R.id.ad_store));
    adView.setPriceView((TextView) adView.findViewById(R.id.ad_price));
    adView.setReviewCountView((TextView) adView.findViewById(R.id.ad_review_count));
    adView.setStarRatingView(adView.findViewById(R.id.ad_star_rating));
}
```
</CodeGroup>

## Samples
- Kotlin samples
  - [Native Ad View (manual)](https://github.com/cleveradssolutions/CAS-Android/blob/master/kotlinSample/src/main/java/com/cleveradssolutions/sampleapp/nativead/NativeAdActivity.kt)
  - [Native Ad Template View](https://github.com/cleveradssolutions/CAS-Android/blob/master/kotlinSample/src/main/java/com/cleveradssolutions/sampleapp/nativead/NativeAdTemplateActivity.kt)
- Java samples
  - [Native Ad View (manual)](https://github.com/cleveradssolutions/CAS-Android/blob/master/javaSample/src/main/java/com/cleveradssolutions/sampleapp/nativead/NativeAdActivity.java)
  - [Native Ad Template View](https://github.com/cleveradssolutions/CAS-Android/blob/master/javaSample/src/main/java/com/cleveradssolutions/sampleapp/nativead/NativeAdTemplateActivity.java)
- Jetpack Compose samples
  - [Native Ad View (manual)](https://github.com/cleveradssolutions/CAS-Android/blob/master/composeSample/src/main/java/com/cleveradssolutions/sampleapp/formats/NativeScreen.kt)
  - [Native Ad Template View](https://github.com/cleveradssolutions/CAS-Android/blob/master/composeSample/src/main/java/com/cleveradssolutions/sampleapp/formats/NativeTemplateScreen.kt)
```

### Enabling test ads

Source: https://production.docs.page/docs/android/enabling-test-ads

```mdx

It's important to enable test ads during development so that you can click on them without charging CAS advertisers.

<Error>  
We strongly suggest that you enable test ads mode when you validate the integration. If you click on too many ads without being in test mode, you risk your account being flagged for invalid activity.
</Error>

There are two ways to get test ads:
- [Enable test ad mode](android/enabling-test-ads#enable-test-ad-mode) for all devices.
- [Set device ids to test ad](android/enabling-test-ads#enable-test-devices).

Ads with Test Ads mode are safe to click. Requests, impressions, and clicks on test ads will not show up in your account's reports.  
Test full-screen ads displays details of CAS integration and tips for solving errors. Go to the Mediation Adapters section to make sure that the advertising networks you want are integrated correctly.

<Image height="500" alt="image" src="/assets/Enabling-test-ads-1.jpg" />
<Image height="500" alt="image" src="/assets/Enabling-test-ads-2.jpg" />

## Enable Debug log mode
The enabled Debug Mode will display a lot of useful information for debugging about the states of the SDK with log tag `CAS`.    
Disabled by default. Disabling Debug Mode may improve application performance. 
<CodeGroup synchronize={true}>
```kotlin
CAS.settings.setDebugMode(true)
````

```java
CAS.settings.setDebugMode(true);
```

</CodeGroup>

<Info>
If you have discovered the problem in the work of the SDK, please provide us with a description of the problem along with the full log of your device.
</Info>

## Enable test ad mode

The quickest way to enable testing is to use test ad mode. The test ad mode are not associated with your CAS account, so there's no risk of your account generating invalid traffic when using these test ad mode.

The easiest way to load test ads is to use: 
<CodeGroup synchronize={true}>
```kotlin
CAS.buildManager().withTestAdMode(true).initialize()
```

```java
CAS.buildManager().withTestAdMode(true).initialize();
```

</CodeGroup>

<Warning>  
Make sure you disable test ad mode and replace test manager ID with your own ad manager ID before publishing your app!
</Warning>

## Enable test devices

If you want to do more rigorous testing with production-looking ads, you can now configure your device as a test device and use your own manager id. Test devices can either be added programmatically.

Follow the steps below to add your device as a test device.

1. Run an app configured with the CAS on device.
2. Check the logcat output for a message that looks like this:

```
To get test ads on this device, set "12345678901234567890123456789012"
```

3. Copy your alphanumeric test device ID to your clipboard.
4. Modify your code to set the test device ID through add `TestDeviceIDs` before CAS manager initialize.

<CodeGroup synchronize={true}>
```kotlin
CAS.settings.testDeviceIDs = setOf("12345678901234567890123456789012")
```

```java
CAS.settings.testDeviceIDs = new HashSet<>(Arrays.asList("12345678901234567890123456789012"));
```
</CodeGroup>

<Info>
Be sure to remove the code that sets these test devices before you release your app.
</Info>

5. Re-run your app.
6. Well done, ads on this device are safe to click. Requests, impressions, and clicks on ads in test mode will not show up in your account's reports.
```

### Google Plays Families Policy

Source: https://production.docs.page/docs/android/google-plays-families-policy

```mdx

<Info>
If your application does not participate in Families Ads program, then you can safely skip this page.   
  
Quote from the [Google Families Ads program page](https://support.google.com/googleplay/android-developer/answer/9283445?hl=en).
</Info>

Google is focused on providing a great experience for families on Google Play and wants to help make sure that any ads served to children are appropriate and compliant with our policies. Review google ads and monetization policy in the [Developer Policy Center](https://play.google.com/about/families/ads-monetization/).  

If your app's target audience includes children and serves ads using an ad SDK, you must use one of the ad SDKs below. The following ad SDKs have self-certified that their compliance with Play’s [Families Ads Program](https://play.google.com/about/monetization-ads/families-ads-program/) requirements.

## Advertising ID
The [advertising ID](https://support.google.com/googleplay/android-developer/answer/6048248?hl=en) is a unique, user-resettable ID for advertising, provided by Google Play services.  

With Android 12 many mediation partners are starting to include the `com.google.android.gms.permission.AD_ID` permission in the SDK’s library manifest but Families Policy, require that apps not use the Ad ID.  
You must prevent the permission from getting merged into your app by including the following element in your manifest.
To do this, just add the following line to your app `AndroidManifest.xml` file inside the `<manifest>` tag but outside the `<application>` tag:
```xml
<manifest>
   <uses-permission android:name="com.google.android.gms.permission.AD_ID" tools:node="remove"/>
</manifest>
```

## Publishing Status Rejected
### Families APIs and SDKs issue
> We have detected that your app includes ads SDKs that have not self-certified their compliance with Families policies or SDKs that are not approved for use in child-directed services.

This may be related to the inclusion of adapters for uncertified ad networks in your build. You are permitted to use only those ad network adapters that are part of the Families Ads Solution.

Another possible cause is the disabled ProGuard in your app's build. Google may identify outdated code in your application and consider it part of an uncertified ad SDK. We recommend enabling ProGuard for the build of your application at all times.
```gradle
android {
    buildTypes {  
        release {  
            minifyEnabled true
            ...
        }  
    }
    ...
}
```
```

### Impression Level Data

Source: https://production.docs.page/docs/android/impression-level-data

```mdx

CAS.AI SDK enables you to access detailed information for each impression through the impressions callback APIs. 
The information includes, for example, which demand source served the ad, the expected or exact revenue associated with it. 
In addition, it contains granular details to allow you to analyze and, ultimately, optimize user acquisition strategies. 

## AdContentInfo

The `com.cleveradssolutions.sdk.AdContentInfo` data structure, which contains information about the loaded/displayed ad.

Additionally to `OnAdImpressionListener`, each ad format has a `getContentInfo()`/`contentInfo` accessor that returns `AdContentInfo`, but the info may be `null` before the ad is loaded.

<CodeGroup synchronize={true}>
```kotlin
val info = eachAd.contentInfo
```

```java
AdContentInfo info = eachAd.getContentInfo();
```
</CodeGroup>


<Property name="format" type="AdFormat">
  The format of the ad that is shown.
</Property>

---

<Property name="sourceName" type="String">
  The display name of the mediated network that purchased the impression.
</Property>

---

<Property name="sourceId" type="Int">
  The ID of the mediated network that purchased the impression. See `AdSource` constants.
</Property>

---

<Property name="sourceUnitId" type="String">
  The Ad Unit ID from the mediated network that purchased the impression.
</Property>

---

<Property name="creativeId" type="String?" optional>
  The Creative ID associated with the ad, if available.
  You can use this ID to report creative issues to the Ad review team. 
</Property>

---

<Property name="revenue" type="Double">
  The revenue generated from the impression, in USD. 
  The revenue value may be either estimated or exact, depending on the precision specified by `revenuePrecision`. 
</Property>

---

<Property name="revenuePrecision" type="Int">
  The precision type of the revenue field. See `AdRevenuePrecision` constants.
</Property>

---

<Property name="revenueTotal" type="Double">
  The accumulated value of user ad revenue in USD from all ad format impressions. 
</Property>

---

<Property name="impressionDepth" type="Int">
  The total number of impressions across all ad formats for the current user, across all sessions. 
</Property>

### User ad summary

CAS count the number of ad impressions and the total revenue of all formats at the time of a new impression.

<CodeGroup synchronize={true}>
```kotlin
val totalImpressions: Int = impression.impressionDepth
val totalRevenue: Double = impression.revenueTotal
```

```java
int totalImpressions = impression.getImpressionDepth();
Double totalRevenue = impression.getRevenueTotal();
```
</CodeGroup>

<Info>
Progress is saved between sessions until the user clears your app's data.
</Info>

### OnAdImpressionListener
A functional interface for listening to ad impression events.

<CodeGroup synchronize={true}>
```kotlin
import com.cleveradssolutions.sdk.OnAdImpressionListener

val impressionListener = OnAdImpressionListener { ad ->
    // Called when an ad impression occurs.
}
```

```java
import com.cleveradssolutions.sdk.OnAdImpressionListener;

final OnAdImpressionListener impressionListener = new OnAdImpressionListener(){  
    @Override  
    public void onAdImpression(@NonNull AdContentInfo ad) {  
        // Called when an ad impression occurs. 
    }  
};
```
</CodeGroup>

Each ad format provides a setter on the ad object for registering a listener to receive `AdContentInfo` with impression details.

<CodeGroup synchronize={true}>
```kotlin
val appOpenAd: CASAppOpen 
appOpenAd.onImpressionListener = impressionListener

val interstitialAd: CASInterstitial 
interstitialAd.onImpressionListener = impressionListener

val rewardedAd: CASRewarded 
rewardedAd.onImpressionListener = impressionListener

val nativeAd: NativeAdContent
nativeAd.onImpressionListener = impressionListener
```

```java
CASAppOpen appOpenAd;
appOpenAd.setOnImpressionListener(impressionListener);

CASInterstitial interstitialAd;
interstitialAd.setOnImpressionListener(impressionListener);

CASRewarded rewardedAd;
rewardedAd.setOnImpressionListener(impressionListener);

NativeAdContent nativeAd;
nativeAd.setOnImpressionListener(impressionListener);
```
</CodeGroup>

## Automatic collect ad revenue

The CAS SDK have features to automatically collect ad revenue to Google Analytics and Tenjin Analytics. Contact your account manager for details of enabling automatic events.

#### Google Analytics

If you haven't already, make sure to complete the following tasks:

1. Set up your project and app as described in [Get Started with Analytics](https://firebase.google.com/docs/analytics/get-started).
2. Make sure that you've linked your Firebase project to a Google Analytics account.
3. Ensure that you've included in your app the CAS SDK 3.5.0+.

To measure ad revenue, CAS SDK log [`ad_impression` events](https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#public-static-final-string-ad_impression) whenever your user sees an advertisement in your app. These events contain details such as the ad platform, source, currency, and value. Optionally, the alternative event name can be `CAS_Impression`.

#### Tenjin
To measure ad revenue with Tenjin Analytics integrate the [Tenjin SDK](https://docs.tenjin.com/docs/android-sdk#basic-integration) or just include Tenjin SDK by CAS Cocoapods:
```kotlin
cas {
    includeTenjinSDK = true
}
```

CAS SDK automatically initializes the Tenjin SDK and sends ILRD if this option is enabled for your application.

## Custom collect ad revenue

The following code shows an implementation example for logging `AD_IMPRESSION` event to Google Analytics.

<CodeGroup synchronize={true}>
```kotlin
override fun onAdImpression(ad: AdContentInfo) {
    val params = Bundle().apply {
        putString(FirebaseAnalytics.Param.AD_PLATFORM, "CAS")
        putString(FirebaseAnalytics.Param.AD_FORMAT, ad.format.toString())
        putString(FirebaseAnalytics.Param.AD_SOURCE, ad.sourceName)
        putString(FirebaseAnalytics.Param.AD_UNIT_NAME, ad.sourceUnitId)
        putDouble(FirebaseAnalytics.Param.VALUE, ad.revenue)
        // All CAS revenue is sent in USD
        putString(FirebaseAnalytics.Param.CURRENCY, "USD")
    }
    FirebaseAnalytics.getInstance(this)
        .logEvent(FirebaseAnalytics.Event.AD_IMPRESSION, params)
}
```

```java
@Override  
public void onAdImpression(@NonNull AdContentInfo ad) {  
    Bundle params = new Bundle();  
    params.putString(FirebaseAnalytics.Param.AD_PLATFORM, "CAS");  
    params.putString(FirebaseAnalytics.Param.AD_FORMAT, ad.getFormat().toString());  
    params.putString(FirebaseAnalytics.Param.AD_SOURCE, ad.getSourceName());  
    params.putString(FirebaseAnalytics.Param.AD_UNIT_NAME, ad.getSourceUnitId());  
    params.putDouble(FirebaseAnalytics.Param.VALUE, ad.getRevenue());  
    // All CAS revenue is sent in USD  
    params.putString(FirebaseAnalytics.Param.CURRENCY, "USD");  

    FirebaseAnalytics.getInstance(this)  
        .logEvent(FirebaseAnalytics.Event.AD_IMPRESSION, params);  
}
```
</CodeGroup>
```

### Initialize CAS SDK

Source: https://production.docs.page/docs/android/initialize-cas

```mdx

The `initializeCAS()` method initializes the SDK and invokes a completion handler once the CAS SDK has been successfully initialized.
This should be done only once, ideally during the app launch.

To begin, create a string constant with your `CAS_ID`. This constant will be needed when creating each ad format instance.

<CodeGroup synchronize={true}>
```kotlin
import com.cleversolutions.ads.android.CAS

class MyApplication : Application() {

    companion object {
        const val CAS_ID: String = BuildConfig.APPLICATION_ID
    }

    override fun onCreate() {
        super.onCreate()

        initializeCAS()
    }
}
```

```java
import com.cleversolutions.ads.android.CAS;

class MyApplication extends Application {

    public static final String CAS_ID = BuildConfig.APPLICATION_ID

    @Override
    protected void onCreate() {
        super.onCreate();
        
        initializeCAS();
    }
}
```
</CodeGroup>

<AccordionGroup>
<Accordion title="What is CAS ID?">

In most cases, a `casId` is the same as your application package name.
- A [package name](https://developer.android.com/studio/build/application-id) uniquely identifies your app on the device and in the Google Play Store.
- The package name value is case-sensitiv and is often referred to as an `APPLICATION_ID`.
- Find your app's package name in your module (app-level) Gradle file, usually `app/build.gradle` (example package name: `com.yourcompany.yourproject`).

</Accordion>
</AccordionGroup>


<Info>
Using `context.packageName` as CAS ID is not safe. If your app does not use `BuildConfig`, it's better to specify a constant.
</Info>

You can skip the manual call for ad initialization, and then the SDK will automatically perform the initialization before the first ad load. However, if it's important for you to change the configuration or listen to states of the Consent Flow, make sure to initialize it at least once before the first ad load.

<CodeGroup synchronize={true}>
```kotlin
private fun initializeCAS() {
    val builder = CAS.buildManager()
        .withCasId(CAS_ID)
        .withCompletionListener(object : InitializationListener {
            override fun onCASInitialized(config: InitialConfiguration) {
                // The CAS SDK initializes if the error is `null`
                val initErrorOrNull: String? = config.error
                val userCountryISO2OrNull: String? = config.countryCode

                // True if the user is protected by GDPR or other regulations
                val protectionApplied: Boolean = config.isConsentRequired

                // The user completes the consent flow
                val consentFlowStatus: Int = config.consentFlowStatus
            }
        })

    builder.build(this)
}
```

```java
void initializeCAS() {
    ManagerBuilder builder = CAS.buildManager()
        .withCasId(MyApplication.CAS_ID)
        .withCompletionListener(new InitializationListener() {  
            @Override  
            public void onCASInitialized(@NonNull InitialConfiguration config) { 
                // The CAS SDK initializes if the error is `null`
                String initErrorOrNull = config.getError();
                String userCountryISO2OrNull = config.getCountryCode();
                
                // True if the user is protected by GDPR or other regulations
                boolean protectionApplied = config.isConsentRequired();

                // The user completes the consent flow
                int consentFlowStatus = config.getConsentFlowStatus(); 
            }  
        });

    builder.build(this);
}
```
</CodeGroup>

The `onCASInitialized` listener may be called with an error. In this case, the SDK will attempt to reinitialize and the listener will be called again until the error is resolved.

<Error>  
Do not initialize mediated advertising SDKs (CAS does that for you).  
Not following this step will result in noticeable integration issues.
</Error>

## Automatic user consent flow
To get consent for collecting personal data of your users, we suggest you use a built-in Consent Flow, comes with a pre-made consent form that you can easily present to your users. That means you no longer need to create your own consent window.  

The user will see the consent flow when your app initialize CAS SDK. When the user completes the flow, the SDK calls your initialization-completion handler.

CAS consent flow is enabled by default. You can disable the consent flow by add disabled  ConsentFlow instance to `withConsentFlow()`:

<CodeGroup synchronize={true}>
```kotlin
builder.withConsentFlow(
    ConsentFlow(/* isEnabled = */ false)
)
```

```java
builder.withConsentFlow(
    new ConsentFlow(/* isEnabled = */ false)
);
```
</CodeGroup>

Make sure to apply all configurations before calling `builder.build()`.

You must wait until the user finishes the consent flow before you initialize third-party SDKs (such as MMPs or analytics SDKs). For this reason, initialize such SDKs from within your initialization-completion callback. If you were to initialize these third-party SDKs before the user completes the consent flow, these third-party SDKs would not be able to access relevant identifiers and you would suffer a material impact on measurement, reporting, and ad revenue.

<Info>
Read more about "Privacy options button" and "Debug geography" on [CAS User Consent Flow page](android/user-consent-flow)
</Info>

## Always test with test ads
When building and testing your apps, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account.

By default, CAS initializes mediation in live mode. To enable test ad mode, you should manually call `initializeCAS()` with the following option:

<CodeGroup synchronize={true}>
```kotlin
builder.withTestAdMode(BuildConfig.DEBUG)
```

```java
builder.withTestAdMode(BuildConfig.DEBUG);
```
</CodeGroup>

For more information about how the CAS.AI SDK's test ads work, see [Enable test ads](android/enabling-test-ads)


## Prohibition on Personal Information from Children
Apps can be marked as child-directed or [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy) applicable through the CAS UI.  

If the app determines that a user falls under COPPA regulations, the `setTaggedAudience()` method must be called before initializing the CAS SDK.

<CodeGroup synchronize={true}>
```kotlin
CAS.settings.setTaggedAudience(Audience.CHILDREN)
```

```java
CAS.settings.setTaggedAudience(Audience.CHILDREN);
```
</CodeGroup>

If your app targets both children and older users, all ads that may be shown to children must comply with COPPA.  
To ensure compliance, a **neutral age screen** must be implemented so that ads unsuitable for children are only shown to appropriate audiences.  
A neutral age screen is a tool—such as an age gate—that verifies a user’s age without encouraging them to misrepresent it, and prevents children from accessing content not intended for them.


## (Optional) Legacy support MediationManager
We are not removing support for managing ads using `MediationManager` at this time, but we recommend migrating to the new `CASInterstitial` and `CASRewarded` components whenever possible.

To continue using `MediationManager`, you still need to specify the ad formats you want to work with, just as before.  

<CodeGroup synchronize={true}>
```kotlin
builder.withAdTypes(AdType.Interstitial, AdType.Rewarded)
```

```java
builder.withAdTypes(AdType.Interstitial, AdType.Rewarded);
```
</CodeGroup>

If your app no longer uses `MediationManager` for Interstitial and Rewarded formats, simply do not define any formats during initialization.

## (Optional) Retrieve the Version Number
To programmatically retrieve the SDK version number at runtime, CAS provides the following method:

<CodeGroup synchronize={true}>
```kotlin
val sdkVersion: String = CAS.getSDKVersion()
```

```java
String sdkVersion = CAS.getSDKVersion();
```
</CodeGroup>

## (Optional) Trial ad-free interval
Set the time interval during which users can enjoy an ad-free experience while retaining access
to Rewarded Ads and App Open Ads formats. This interval is defined from the moment of the initial
app installation, in seconds. Within this interval, users enjoy privileged access to the
application's features without intrusive advertisements.

<CodeGroup synchronize={true}>
```kotlin
val secondsIn7Days = 604800 
CAS.settings.setTrialAdFreeInterval(secondsIn7Days)
```

```java
int secondsIn7Days = 604800;
CAS.settings.setTrialAdFreeInterval(secondsIn7Days);
```
</CodeGroup>

## Complete sample
- [Kotlin Sample Application](https://github.com/cleveradssolutions/CAS-Android/blob/master/kotlinSample/src/main/java/com/cleveradssolutions/sampleapp/SampleApplication.kt)
- [Java Sample Application](https://github.com/cleveradssolutions/CAS-Android/blob/master/javaSample/src/main/java/com/cleveradssolutions/sampleapp/SampleApplication.java)
```

### Interstitial Ads

Source: https://production.docs.page/docs/android/interstitial-ads

```mdx

Interstitial ads are full-screen ads that cover the interface of their host app.
They're typically displayed at natural transition points in the flow of an app, such as between screens or during the pause between levels in a game. 
When an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.  

Below is a diagram showing the ad lifecycle.
<Image zoom src="/assets/Lifecycle-Screen-Ad.png" alt="Diagram" height="500" />


## Create Ad instance
Ad instance can be initialized along with the activity before `onCreate`.

<CodeGroup synchronize="true">
```kotlin
import com.cleveradssolutions.sdk.screen.CASInterstitial

class MyActivity : Activity() {

    private val interstitialAd = CASInterstitial(MyApplication.CAS_ID)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ...
    }
}
```

```java
import com.cleveradssolutions.sdk.screen.CASInterstitial;

class MyActivity extends Activity {

    final CASInterstitial interstitialAd = new CASInterstitial(MyApplication.CAS_ID);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ...
    }
}
```
</CodeGroup>

The SDK provides the capability to create and precache multiple ad instances, enabling uninterrupted sequential ad display. CAS SDK will load mediation ads in order for each created instance.

## Create Ad Content callback

The `com.cleveradssolutions.sdk.screen.ScreenAdContentCallback` handles events related to displaying your `CASInterstitial`. Callbacks are called on the main thread. Before showing ad, make sure to set `contentCallback`.

<CodeGroup synchronize="true">
```kotlin
val adContentCallback = object : ScreenAdContentCallback {
    override fun onAdLoaded(ad: AdContentInfo) {
        // (Optional) Called when the ad content has been successfully loaded.
    }

    override fun onAdFailedToLoad(format: AdFormat, error: AdError) {
        // (Optional) Called when the ad content fails to load.
    }

    override fun onAdFailedToShow(format: AdFormat, error: AdError) {
        // (Optional) Called when the ad content fails to show.
    }

    override fun onAdShowed(ad: AdContentInfo) {
        // (Optional) Called when the ad content is successfully shown.
    }

    override fun onAdClicked(ad: AdContentInfo) {
        // (Optional) Called when the ad content is clicked by the user.
    }

    override fun onAdDismissed(ad: AdContentInfo) {
        // (Optional) Called when the ad content is dismissed.
    }
}
```

```java
final ScreenAdContentCallback adContentCallback = new ScreenAdContentCallback() {  
    @Override  
    public void onAdLoaded(@NonNull AdContentInfo ad) {  
        // (Optional) Called when the ad content has been successfully loaded.  
    }  
  
    @Override  
    public void onAdFailedToLoad(@NonNull AdFormat format, @NonNull AdError error) {  
        // (Optional) Called when the ad content fails to load.  
    }  
  
    @Override  
    public void onAdFailedToShow(@NonNull AdFormat format, @NonNull AdError error) {  
        // (Optional) Called when the ad content fails to show.  
    }  
  
    @Override  
    public void onAdShowed(@NonNull AdContentInfo ad) {  
        // (Optional) Called when the ad content is successfully shown.  
    }  
  
    @Override  
    public void onAdClicked(@NonNull AdContentInfo ad) {  
        // (Optional) Called when the ad content is clicked by the user.  
    }  
  
    @Override  
    public void onAdDismissed(@NonNull AdContentInfo ad) {  
        // (Optional) Called when the ad content is dismissed.  
    }  
};
```
</CodeGroup>

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](android/impression-level-data).
- Attempting to load a new ad from the `onAdFailedToLoad()` method is strongly discouraged. Limit ad load retries to avoid continuous failed ad requests in situations such as limited network connectivity.
- When an error occurs during ad impression, executed the `onAdFailedToShow` only. In this case the `onAdDismissed` will not be executed, since the impression is not considered successful.
</Info>

## Load Ad

The next step is to fill out the `load()` method and handle the ad load callbacks. 

<CodeGroup synchronize="true">
```kotlin
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    interstitialAd.contentCallback = adContentCallback
    interstitialAd.load(this)
}
```

```java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    interstitialAd.setContentCallback(adContentCallback);
    interstitialAd.load(this);
}
```
</CodeGroup>

You can use ad load calls to build up a cache of preloaded ads before you intend to show them, so that ads can be shown with zero latency when needed. Since ads expire after an hour, you should clear this cache and reload with new ads every hour.

### Autoload mode

If enabled, the ad will automatically load new content when the current ad is dismissed or completed. Additionally, it will automatically retry loading the ad if an error occurs during the loading process.

<CodeGroup synchronize="true">
```kotlin
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    interstitialAd.contentCallback = adContentCallback
    interstitialAd.isAutoloadEnabled = true
}
```

```java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    interstitialAd.setContentCallback(adContentCallback);
    interstitialAd.setAutoloadEnabled(true);
}
```
</CodeGroup>

By default autoload disabled.

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements.

The placement name should be set before showing the ads. Maximum 100 characters allowed for the placement name.

<CodeGroup synchronize="true">
```kotlin
interstitialAd.placement = "BestPlace"
```

```java
interstitialAd.setPlacement("BestPlace")
```
</CodeGroup>

## Show Ad

Interstitial ads should be displayed during natural pauses in the flow of an app. Between levels of a game is a good example, or after the user completes a task. To show an interstitial, use the `show(Activity?)` method.

<CodeGroup synchronize="true">
```kotlin
interstitialAd.show(this)
```

```java
interstitialAd.show(MyActivity.this);
```
</CodeGroup>

Starting with CAS SDK version 4.3.0, all ads functions can be safely called from any thread.

### Autoshow mode

Use the `isAutoshowEnabled` property to automatically show a loaded ad when the user returns to the app. 

<CodeGroup synchronize="true">
```kotlin
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    ...
    interstitialAd.isAutoshowEnabled = true
}
```

```java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ...
    interstitialAd.setAutoshowEnabled(true);
}
```
</CodeGroup>

By default autoshow disabled.

### Checking Ad Availability

Use `isLoaded()` to check whether an ad is currently loaded. 

<CodeGroup synchronize="true">
```kotlin
if (interstitialAd.isLoaded) {
}
```

```java
if (interstitialAd.isLoaded()) {
}
```
</CodeGroup>

Even if `isLoaded()` returns `true`, it does not guarantee that the ad will be shown successfully — various issues may still prevent it from being displayed. We strongly recommend handling potential display failures via `onAdFailedToShow(error)` callback to ensure a smoother user experience.

By relying on these callbacks, you ensure that your application can react appropriately to real-time conditions, rather than making assumptions based on ad load state at a single point in time.

## Minimum interval between impressions

You can limit the posting of an interstitial ad to a period of time in seconds after the ad is closed, during which display attempts will fail. Unlimited by default 0 seconds.
That the interval starts only after the Interstitial `onAdDismissed()`.
During interval after ad closed, display attempts will fire event `onAdFailedToShow()` with `AdErrorCode.NOT_PASSED_INTERVAL`.

<CodeGroup synchronize="true">
```kotlin
interstitialAd.minInterval = interval
```

```java
interstitialAd.setMinInterval(interval);
```
</CodeGroup>

If you need to wait for a period of time after the start of the app or after showing a Rewarded Ad until next Interstitial Ad impression then call the following method: 

<CodeGroup synchronize="true">
```kotlin
interstitialAd.restartInterval()
```

```java
interstitialAd.restartInterval();
```
</CodeGroup>

You can define a different interval for each ad instance. However, the countdown will always start from the moment any ad instance is closed within the session.

## Mute Ad sounds

Indicates if the application’s audio is muted. Affects initial mute state for all ads.
Use this method only if your application has its own volume controls. 

<CodeGroup synchronize="true">
```kotlin
CAS.settings.mutedAdSounds = true
```

```java
CAS.getSettings().setMutedAdSounds(true);
```
</CodeGroup>

## Release ad resource

It is important to `destroy()` loaded but not displayed ads. 

<CodeGroup synchronize="true">
```kotlin
override fun onDestroy() {
    interstitialAd.destroy()
    super.onDestroy()
}
```

```java
@Override  
protected void onDestroy() {  
    interstitialAd.destroy();  
    super.onDestroy();  
}
```
</CodeGroup>

## Samples

- [Kotlin Interstitial Ad Activity](https://github.com/cleveradssolutions/CAS-Android/blob/master/kotlinSample/src/main/java/com/cleveradssolutions/sampleapp/interstitial/InterstitialAdActivity.kt)
- [Java Interstitial Ad Activity](https://github.com/cleveradssolutions/CAS-Android/blob/master/javaSample/src/main/java/com/cleveradssolutions/sampleapp/interstitial/InterstitialAdActivity.java)

## Some best practices

#### Consider whether interstitial ads are the right type of ad for your app.

Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, like sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it's easy to present an interstitial ad without disrupting their experience. Make sure you consider at which points in your app's workflow you'll display interstitial ads and how the user is likely to respond.

#### Remember to pause the action when displaying an interstitial ad.

There are a number of different types of interstitial ads: text, image, video, and more. It's important to make sure that when your app displays an interstitial ad, it also suspends its use of some resources to allow the ad to take advantage of them. For example, when you make the call to display an interstitial ad, be sure to pause any audio output being produced by your app.

#### Allow for adequate loading time.

Just as it's important to make sure you display interstitial ads at an appropriate time, it's also important to make sure the user doesn't have to wait for them to load. Loading the ad in advance by calling `load()` before you intend to call `show()` can ensure that your app has a fully loaded interstitial ad at the ready when the time comes to display one.

#### Don't flood the user with ads.

While increasing the frequency of interstitial ads in your app might seem like a great way to increase revenue, it can also degrade the user experience and lower clickthrough rates. Make sure that users aren't so frequently interrupted that they're no longer able to enjoy the use of your app.
```

### Load Native Ads

Source: https://production.docs.page/docs/android/load-native-ads

```mdx

Native ads are advertising assets seamlessly integrated into the user interface using components that are native to the platform.
They are displayed through the same views you use to construct your app's layouts, allowing for a cohesive user experience. 
Additionally, these ads can be customized to align with your app's visual design, ensuring they feel like a natural part of the content rather than intrusive advertisements.

Below is a diagram showing the ad lifecycle.
<Image zoom src="/assets/Lifecycle-Native-Ad.png" alt="Diagram" height="500" />


## Create Ad Content callback
A `com.cleveradssolutions.sdk.nativead.NativeAdContentCallback` class for handling events related to native ad content.  

<CodeGroup synchronize={true}>
```kotlin
val nativeAdCallback = object : NativeAdContentCallback() {
    override fun onNativeAdLoaded(nativeAd: NativeAdContent,ad: AdContentInfo) {
        keepNativeAdInMemory(nativeAd)
        registerNativeAdContent(nativeAd)
    }
    override fun onNativeAdFailedToLoad(error: AdError) {
        // (Optional) Handle Ad load errors
    }
    override fun onNativeAdFailedToShow(nativeAd: NativeAdContent,error: AdError) {
        // (Optional) Handle Ad render errors.
        // Called from CASNativeView.bindAdContent(nativeAd)
    }
    override fun onNativeAdClicked(nativeAd: NativeAdContent,ad: AdContentInfo) {
        // (Optional) Called when the native ad is clicked by the user.
    }
}
```

```java
final NativeAdContentCallback nativeAdCallback =  new NativeAdContentCallback() {  
    @Override  
    public void onNativeAdLoaded(@NonNull NativeAdContent nativeAd, @NonNull AdContentInfo ad) {  
        keepNativeAdInMemory(nativeAd);  
        registerNativeAdContent(nativeAd);  
    }  
    @Override  
    public void onNativeAdFailedToLoad(@NonNull AdError error) {  
        // (Optional) Handle Ad load errors    
    }  
    @Override  
    public void onNativeAdFailedToShow(@NonNull NativeAdContent nativeAd, @NonNull AdError error) {  
        // (Optional) Handle Ad render errors.   
        // Called from CASNativeView.bindAdContent(nativeAd)   
    }  
    @Override  
    public void onNativeAdClicked(@NonNull NativeAdContent nativeAd, @NonNull AdContentInfo ad) {  
        // (Optional) Called when the native ad is clicked by the user.    
    }  
};
```
</CodeGroup>

## Load ad

Native ads are loaded with the `com.cleveradssolutions.sdk.nativead.CASNativeLoader` class.

<Tabs groupId="platform">
<TabItem label="Kotlin" value="kotlin">
```kotlin
fun loadNativeAd() {
    val adLoader = CASNativeLoader(this, MyApplication.CAS_ID, nativeAdCallback)
    adLoader.adChoicesPlacement = AdChoicesPlacement.TOP_LEFT // by default
    adLoader.isStartVideoMuted = true // by default
    adLoader.load()
}

fun keepNativeAdInMemory(nativeAd: NativeAdContent) {
    loadedNativeAds.add(nativeAd)
}
```

</TabItem>
<TabItem label="Java" value="java">
```java
void loadNativeAd() {  
    CASNativeLoader adLoader = new CASNativeLoader(MyActivity.this, MyApplication.CAS_ID, nativeAdCallback);  
    adLoader.setAdChoicesPlacement(AdChoicesPlacement.TOP_LEFT); // by default  
    adLoader.setStartVideoMuted(true); // by default
    adLoader.load();  
}

void keepNativeAdInMemory(NativeAdContent nativeAd) {
    loadedNativeAds.add(nativeAd);
}
```

</TabItem>
<TabItem label="Compose" value="compose">
```kotlin
@Composable
fun NativeAdScreen() {
    val context = LocalContext.current
    var loadedNativeAds by remember { mutableStateOf<List<NativeAdContent>>(emptyList()) }
    var isDestroyed = false

    fun keepNativeAdInMemory(nativeAd: NativeAdContent) {
        loadedNativeAds = loadedNativeAds + nativeAd
    }

    // other functions here

    DisposableEffect(Unit) {
        val adLoader = CASNativeLoader(context, MyApplication.CAS_ID, nativeAdCallback)
        adLoader.adChoicesPlacement = AdChoicesPlacement.TOP_LEFT // by default
        adLoader.isStartVideoMuted = true // by default
        adLoader.load()

        onDispose { isDestroyed = true }
    }
}
```

</TabItem>
</Tabs>

After a call to `load()`, a single callback is made to the previously defined `NativeAdContentCallback` to deliver the native ad object or report an error.

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements.

The placement name should be set before loading the ads. Maximum 100 characters allowed for the placement name.

<CodeGroup synchronize="true">
```kotlin
adLoader.placement = "BestPlace"
```

```java
adLoader.setPlacement("BestPlace")
```

</CodeGroup>

### Autoload Ad mode

The `CASNativeLoader` does not have an autoload ad mode like other ad formats, so you need to implement error handling and ad reloading manually.

## Load multiple ads (optional)

The `load()` method takes an additional parameter: the number of ads the SDK should attempt to load for the request. It's not guaranteed that the SDK will return the exact number of ads requested.

<CodeGroup synchronize={true}>
```kotlin
val maxNumberOfAdsToLoad = 3
adLoader.load(maxNumberOfAdsToLoad)
```

```java
int maxNumberOfAdsToLoad = 3;
adLoader.load(maxNumberOfAdsToLoad);
```
</CodeGroup>

The `onNativeAdLoaded` will be called multiple times, once for each ad that is successfully loaded, up to the specified maximum number of ads.
If the load operation fails, the `onNativeAdFailedToLoad` will be called once with the error details.

Apps requesting multiple ads should call `CASNativeLoader.isLoading` in their callback implementations to determine whether the loading process has finished.

<CodeGroup synchronize={true}>
```kotlin
override fun onNativeAdLoaded(nativeAd: NativeAdContent,ad: AdContentInfo) {
    keepNativeAdInMemory(nativeAd)
    registerNativeAdContent(nativeAd)

    if (adLoader.isLoading) {
        // The AdLoader is still loading ads.
        // Expect more onNativeAdLoaded or onNativeAdFailedToLoad callbacks.
    } else {
        // The AdLoader has finished loading ads.
    }
}
```

```java
@Override  
public void onNativeAdLoaded(@NonNull NativeAdContent nativeAd, @NonNull AdContentInfo ad) {  
    keepNativeAdInMemory(nativeAd);
    registerNativeAdContent(nativeAd);
    
    if (adLoader.isLoading()) {
        // The AdLoader is still loading ads.
        // Expect more onNativeAdLoaded or onNativeAdFailedToLoad callbacks.
    } else {
        // The AdLoader has finished loading ads.
    }   
} 
```
</CodeGroup>

## Release ad resources

It’s crucial to call the `destroy()` method on all loaded native ads, even if they were not used or referenced. This action releases utilized resources and helps prevent memory leaks.

When you invoke the `load()` function, the `CASNativeLoader` will continue running until the ad finishes loading. This can lead to the `NativeAdContentCallback` being triggered after the `Activity` has been destroyed or at unexpected times. Therefore, you should implement checks to destroy the loaded ad if you do not plan to display it to the user.

<CodeGroup synchronize={true}>
```kotlin
override fun onNativeAdLoaded(nativeAd: NativeAdContent, ad: AdContentInfo) {
    // If this callback is invoked after the activity is destroyed,
    // call destroy and return to avoid potential memory leaks.
    // Note: `isDestroyed()` is a method available on Activity.
    if (isDestroyed) {
        nativeAd.destroy()
        return
    }
    keepNativeAdInMemory(nativeAd)
    registerNativeAdContent(nativeAd)
}
```

```java
@Override
public void onNativeAdLoaded(@NonNull NativeAdContent nativeAd, @NonNull AdContentInfo ad) {
    // If this callback is invoked after the activity is destroyed,
    // call destroy and return to avoid potential memory leaks.
    // Note: `isDestroyed()` is a method available on Activity.
    if (isDestroyed()) {
        nativeAd.destroy();
        return;
    }
    keepNativeAdInMemory(nativeAd);
    registerNativeAdContent(nativeAd);
}
```
</CodeGroup>

Make sure to destroy all `NativeAdContent` references in your activity’s `onDestroy()` function:

<Tabs groupId="platform">
<TabItem label="Kotlin" value="kotlin">
```kotlin
override fun onDestroy() {
    loadedNativeAds.forEach { it.destroy() }
    super.onDestroy()
}
```

</TabItem>
<TabItem label="Java" value="java">
```java
@Override
public void onDestroy() {
    for (NativeAdContent ad : loadedNativeAds) {
        ad.destroy();
    }
    super.onDestroy();
}
```

</TabItem>
<TabItem label="Compose" value="compose">
```kotlin
DisposableEffect(Unit) {
    onDispose {
        isDestroyed = true
        adContents.forEach { it.destroy() }
    }
}
```

</TabItem>
</Tabs>
```

### Manual setup

Source: https://production.docs.page/docs/android/manual-setup

```mdx

Follow the step-by-step guide below. Optional steps can be completed at your discretion.

### 1. Include maven repositories
Find the repositories on the [Home page](android).

### 2. Add the dependencies for the CAS SDK to your module-level build file:
<CodeGroup synchronize={true}>
```kotlin
dependencies {
    implementation("com.cleveradssolutions:cas-sdk:{{ versions.android }}")
    ...
}
```

```groovy
ependencies {
    implementation 'com.cleveradssolutions:cas-sdk:{{ versions.android }}")
    ...
}
```
</CodeGroup>
All adapters for supported networks are found in the `com.cleveradssolutions` dependency group, and do not require additional SDK dependencies to be added.  

<Card title="Subscribe" icon="github" href="https://github.com/cleveradssolutions/CAS-Android/subscription">
SDK and Adapters versions are updated frequently and you should use the latest versions. 

Subscribe to receive notifications about CAS updates.
</Card>

### 3. Add mediated networks that are fully compatible with Google Play Families policies:

<CodeGroup synchronize={true}>
```kotlin
implementation("com.cleveradssolutions:ironsource:+")   // IronSource
implementation("com.cleveradssolutions:google:+")       // Google Ads | Admob
implementation("com.cleveradssolutions:unity:+")        // Unity Ads
implementation("com.cleveradssolutions:vungle:+")       // LiftoffMonetize
implementation("com.cleveradssolutions:inmobi:+")       // InMobi
implementation("com.cleveradssolutions:chartboost:+")   // Chartboost
implementation("com.cleveradssolutions:fyber:+")        // DT Exchange 
implementation("com.cleveradssolutions:kidoz:+")        // Kidoz
implementation("com.cleveradssolutions:superawesome:+") // SuperAwesome
```

```groovy
implementation 'com.cleveradssolutions:ironsource:+'   // IronSource
implementation 'com.cleveradssolutions:google:+'       // Google Ads | AdMob
implementation 'com.cleveradssolutions:unity:+'        // Unity Ads
implementation 'com.cleveradssolutions:vungle:+'       // LiftoffMonetize
implementation 'com.cleveradssolutions:inmobi:+'       // InMobi
implementation 'com.cleveradssolutions:chartboost:+'   // Chartboost
implementation 'com.cleveradssolutions:fyber:+'        // DT Exchange
implementation 'com.cleveradssolutions:kidoz:+'        // Kidoz
```
</CodeGroup>

<Info>
- Read more about the adapter versions [here](https://github.com/cleveradssolutions/CAS-Android/blob/master/Adapters/README.md).
- For applications targeting children or audiences under the age of 13, monetization is only allowed using ad SDKs that are certified under the **Google Play Families Program**.
- **Kidoz and SuperAwesome** provide monetization for children adience only.
</Info>

### 4. Add mediated networks that are always recommended for app monetization.
For applications not targeting children (adult or mixed audiences), it is recommended to include the following dependencies **in addition to those listed above**.

<CodeGroup synchronize={true}>
```kotlin
implementation("com.cleveradssolutions:cas-exchange:+") // CASExchange
implementation("com.cleveradssolutions:mintegral:+")    // Mintegral
implementation("com.cleveradssolutions:applovin:+")     // AppLovin
implementation("com.cleveradssolutions:facebook:+")     // Meta Audience Network
implementation("com.cleveradssolutions:pangle:+")       // Pangle
implementation("com.cleveradssolutions:yango:+")        // Yango Ads
implementation("com.cleveradssolutions:bigo:+")         // Bigo
```

```groovy
implementation 'com.cleveradssolutions:cas-exchange:+' // CASExchange
implementation 'com.cleveradssolutions:mintegral:+'    // Mintegral
implementation 'com.cleveradssolutions:applovin:+'     // AppLovin
implementation 'com.cleveradssolutions:facebook:+'     // Meta Audience Network
implementation 'com.cleveradssolutions:pangle:+'       // Pangle
implementation 'com.cleveradssolutions:yandex:+'       // Yandex Ads
implementation 'com.cleveradssolutions:bigo:+'         // Bigo
```
</CodeGroup>
### 5. (Optional) Add other mediated networks.

<CodeGroup synchronize={true}>
```kotlin
implementation("com.cleveradssolutions:ysonetwork:+")   // YSO Network
implementation("com.cleveradssolutions:ogury:+")        // Ogury
implementation("com.cleveradssolutions:hyprmx:+")       // HyprMX
implementation("com.cleveradssolutions:startio:+")      // StartIO
implementation("com.cleveradssolutions:prado:+")        // Prado
```

```groovy
implementation 'com.cleveradssolutions:ysonetwork:+'   // YSO Network
implementation 'com.cleveradssolutions:ogury:+'        // Ogury
implementation 'com.cleveradssolutions:hyprmx:+'       // HyprMX
implementation 'com.cleveradssolutions:startio:+'      // StartIO
```
</CodeGroup>
### 6. (Optional) Add Cross Promo adapter.  
   Contact our account manager if you are interested in cross-promotion.

<CodeGroup synchronize={true}>
```kotlin
implementation("com.cleveradssolutions:cas-promo:+")
```

```groovy
implementation 'com.cleveradssolutions:cas-promo:+'
```
</CodeGroup>

### 7. (Optional) Add **Closed beta** mediated networks.

<CodeGroup synchronize={true}>   
```kotlin
implementation("com.cleveradssolutions:maticoo:+")      // Maticoo
implementation("com.cleveradssolutions:smaato:+")       // Smaato
implementation("com.cleveradssolutions:verve:+")        // Verve
```

```groovy
implementation 'com.cleveradssolutions:maticoo:+'  // Maticoo
implementation 'com.cleveradssolutions:prado:+'    // Prado
implementation 'com.cleveradssolutions:smaato:+'   // Smaato
```
</CodeGroup>

<Info>
Access to the monetization of the beta ad sources is closed. Please note that you may need to add additional [maven repositories](android) for your project.
If you would like to monetize by one of these ad sources, please contact your account manager.
</Info>

### 8.  Add Play Services Ads identifier
The [Advertising ID](https://support.google.com/googleplay/android-developer/answer/6048248?hl=en) is a unique, user-resettable, and user-deletable ID for advertising, provided by Google Play services.

Add the Play Services Ads identifier into the `dependencies` block to allow GAID information to be retrieved.

<CodeGroup synchronize={true}>
```kotlin
implementation("com.google.android.gms:play-services-ads-identifier:18.1.0")
```

```groovy
implementation 'com.google.android.gms:play-services-ads-identifier:18.1.0'
```
</CodeGroup>

Additionally, apps will need to declare a Google Play Services normal permission in the `AndroidManifest.xml` file as follows:
```xml
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>
```

Some SDKs, such as the Google Mobile Ads SDK may already declare this permission in the SDK’s library manifest.
> If your app uses these SDKs as dependencies, the AD_ID permission from the SDK’s library manifest will be merged with your app’s main manifest by default, even if you don’t explicitly declare the permission in your app’s main manifest.

To prevent the permission from getting merged into your app by including the following element in your manifest:
```xml
<uses-permission android:name="com.google.android.gms.permission.AD_ID" tools:node="remove"/>
```

To learn more about the `com.google.android.gms.permission.AD_ID` permission declaration, including how to disable it, refer to this [Play Console article](https://support.google.com/googleplay/android-developer/answer/6048248).

<Info>
An application must not use an advertising identifier if **at least one** of the following conditions is true:
- The app’s target audience includes **only children**, as defined in the [Families Policy](https://support.google.com/googleplay/android-developer/answer/9893335?sjid=10683822576513227860-EU).
- The app is being built for **devices that do not use Google Play Services** (e.g. Amazon or Huawei devices).
</Info>

### 9. Enable code minify
Enabling `minifyEnabled` is a crucial step in optimizing your mobile application, especially when integrating ad mediation SDKs that augment your codebase's size. By leveraging code minification, you not only reduce the overall footprint of your app but also enhance its performance, security, and compatibility.
```kotlin
android {
    buildTypes {  
        release {  
            isMinifyEnabled = true
            ...
        }  
    }
    ...
}
```

<Info>
The CAS SDK and adapters come bundled with the required ProGuard rules in the AARs. Therefore, you do not need to add any additional ProGuard rules to your project.
</Info>

### 10. Click Sync Now gradle files.

### 11. Link the project
To link your project with the mediation settings, you need to have a registered account and an application in the CAS system.

If you haven't created an CAS account and registered the app yet, now's a great time to do so.
If you just want to experiment or test the SDK, you can skip link your project.

1. Sign In https://cas.ai.
2. Select the Applications section on the right panel.
3. Click the plus(**+**) button and follow the instructions on the form. It may take up to 30 minutes to register the app in the CAS system.
4. After the registration completed, click the **Action** button in the row of your application

![dashboardcasapps](https://user-images.githubusercontent.com/22005013/225905839-6b494a90-a400-49d9-a070-ae930e4ff225.jpg)  

5. Click **Download CAS settings** button. The CAS SDK uses a mediation configuration caching system to handle unexpected situations. 
6. A `cas_settings[settings_id].json` file will be downloaded.
7. Move your config file into the **module (app-level)** `/src/res/raw/` directory of your app.  

<Accordion title="What do you need to know about this config file?">

- The CAS config file contains unique, but non-secret identifiers for your project. 
- The configuration file is updated frequently, so we recommend that you regularly download the latest file for each new release.
- Please do not change the name of the file. Make sure the config file name is not appended with additional characters, like `(2)`.
- The `[settings_id]` is the internal unique identifier of the resource.  
- If you have multiple CAS manager IDs in your project, you must associate each CAS ID with a registered app in the CAS console so that each app can have its own `cas_settings[settings_id].json` file.
  
</Accordion>
  

### 12. Add Google Ads App ID 
CAS assigns a new Google Ads (AdMob) App ID for your application to the correct operation of all features. Find the ID for each application in the CAS UI.

1. After the registration completed, click the **Action** button in the row of your application
2. Click the **Show AdMob App ID** button.
3. Copy the id from the form.
4. Add a `<meta-data>` tag with `android:name="com.google.android.gms.ads.APPLICATION_ID"` in your app's `AndroidManifest.xml` file.
5. Insert AdMob app ID to `android:value`, surrounded by quotation marks, as shown below.
```xml
<manifest>
  <application>
    ...
    <!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
    <meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
  </application>
</manifest>
```
In a real app, replace the sample app ID with your **actual AdMob app ID**. You can use the sample ID if you're just experimenting with the SDK in a Hello World app.

Also, note that failure to add the `<meta-data>` tag exactly as shown results in a crash with the message: `Missing application ID`

<Error>  
You cannot use your own identifier and must replace it with a new one generated by CAS system. 
</Error>
```

### Mediated Networks

Source: https://production.docs.page/docs/android/mediated-networks

```mdx

Advanced publishers who are familiar with ad network integrations can choose their own set of adapters. If you have any questions or need assistance, please contact your account manager.  

Feel free not to use ready-made (`Optimal` or `Families`) solutions, and choose which mediated ad networks you want to integrate by copy following adapter names to `build.gradle` file: 

Just specify `true` for the adapters you want to use and all the necessary dependencies will be included in your application automatically.

```kotlin
cas {  
    adapters {  
        appLovin = true  
        audienceNetwork = true  
        bidease = true  
        bigoAds = true  
        bluesea = true  
        casExchange = true  
        chartboost = true  
        dtExchange = true  
        googleAds = true  
        hyprMX = true  
        inMobi = true  
        ironSource = true  
        kidoz = true  
        liftoffMonetize = true  
        maticoo = true  
        mintegral = true  
        moloco = true  
        monetrix = true  
        ogury = true  
        pangle = true  
        prado = true  
        smaato = true  
        startIO = true  
        superAwesome = true  
        unityAds = true  
        verve = true  
        yangoAds = true  
        ysoNetwork = true  
    }  
}
```

The adapters are sorted alphabetically in the list.

<Info>
- Read more about the adapter versions [here](https://github.com/cleveradssolutions/CAS-Android/blob/master/Adapters/README.md).
- The Meta Audience Network requires [Additional implementations](additional-meta-audiencenetwork-steps).
- The HyprMX is focused on the USA and Canada regions only. Your apps must be approved for monetization.
</Info>

## Closed beta ad adapters

<Warning>  
Access to the monetization of the beta ad sources is closed.  
If you would like to monetize by one of these ad sources, please contact your account manager.
</Warning>

```kotlin
cas {  
    adapters {  
        bidmachine = true  
        displayIO = true  
        pubmatic = true  
    }  
}
```

<Info>
Please note that you may need to add additional [maven repositories](android) for your project.
</Info>

## Cross promotion adapter
Cross promotion is an app marketing strategy in which app developers promote one of their titles on another one of their titles. Cross promoting is especially effective for developers with large portfolios of games as a means to move users across titles and use the opportunity to scale each of their apps. This is most commonly used by hyper-casual publishers who have relatively low retention, and use cross promotion to keep users within their app portfolio.

```kotlin
cas {  
    adapters {  
        crossPromo = true  
    }  
}
```

<Success>
Contact our account manager if you are interested in cross-promotion.
</Success>
```

### Native Ad assets

Source: https://production.docs.page/docs/android/native-ad-assets

```mdx

| Name             | Type                          | Required    | Included                   | Description                                                                                                                                 |
| ---------------- | ----------------------------- | ----------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| adChoicesView    | CASChoicesView                | Yes         | Always                     | Read below about [AdChoices overlay](android/native-ad-assets#adchoices-overlay).                                                                                   |
| mediaView        | CASMediaView                  | Yes         | Always                     | Read below about [Media Content](android/native-ad-assets#media-content).                                                                                           |
| headlineView     | TextView                      | Yes         | Always                     | The headline text of the native ad.                                                                                                         |
| adLabelView      | TextView                      | If provided | Not always                 | Read below about [Ad attribution](android/native-ad-assets#ad-attribution).                                                                                         |
| callToActionView | Button                        | If provided | Not always                 | Button that encourages users to take action (for example, "Visit site" or "Install"). This text may truncate after 15 characters.           |
| iconView         | TextView                      | If provided | Always for app install ads | The small app icon or advertiser logo with square aspect ratio (1:1).                                                                       |
| bodyView         | TextView                      | No          | Always                     | The body text of the native ad. This text may truncate after 90 characters.                                                                 |
| advertiserView   | TextView                      | No          | Always for content ads     | Text that identifies the advertiser (for example, advertiser name, brand name, or visible URL). This text may truncate after 25 characters. |
| storeView        | TextView                      | No          | Not always                 | The name of the store where the product or service is available.                                                                            |
| priceView        | TextView                      | No          | Not always                 | The price of the product or service advertised.                                                                                             |
| reviewCountView  | TextView                      | No          | Not always                 | The number of reviews the app has received.                                                                                                 |
| starRatingView   | CASStarRatingView or any View | No          | Not always                 | Read below about [Star Rating](android/native-ad-assets#star-rating-view).                                                                                          |

## Advertising requirements
- Native ads smaller than 32x32dp won't serve. Ads this small can be difficult to see or interact with and may adversely affect the display quality of advertiser assets.
- For native video ads, the main asset `mediaView` must be at least 120x120dp. Video ads won't serve to implementations with main asset `CASMediaView` smaller than 120dp in any dimension.
- The Ad View must be visible and non-transparent.
- At a single point in time, a loaded ad can only be served in one View. Simultaneous display of a single ad in multiple Views may result in the loss of impression.
- The app must be active (not running in the background).
- Don't edit the text content of assets.
- Don't edit the content of images.

### Media Content
You're required to use the `CASMediaView` asset instead of the `ImageView` asset if you want to include a main image asset in the layout for your native ad.  
The `CASMediaView` is a special `View` designed to display the main media asset, either video or image. Can be defined in an XML layout or constructed dynamically. It should be placed within the view hierarchy of a `CASNativeView`, just like any other asset view.  The media view will be populated automatically when calling `bindAdContent()`.
- Check if the video asset is available using `nativeAd.hasVideoContent`.
- Check if the image asset is available using `nativeAd.hasImageContent`.
- Obtain the recommended aspect ratio of the media content using `nativeAd.getMediaContentAspectRatio`.

### Ad attribution
You must clearly display the text "Ad", "Advertisement", or "Sponsored" (localized appropriately). The badge is required to be a minimum of 15px height and width. Ad attribution must be displayed at the top of the ad.

### AdChoices overlay
Ad AdChoices overlay logo must be displayed at the top of the ad 
Each ad view must display an AdChoices overlay logo. Also, it's important that the AdChoices overlay be easily seen, so choose background colors and images appropriately.

#### Use AdChoices placements
An AdChoices overlay can be added by the SDK if `CASNativeView.adChoicesView` not registered. Leave space in your preferred corner of your native ad view for the automatically inserted AdChoices logo.  
Use `AdChoicesPlacement` constants to set preferred corner. 

<CodeGroup synchronize={true}>
```kotlin
adLoader.adChoicesPlacement = AdChoicesPlacement.TOP_RIGHT
```

```java
adLoader.setAdChoicesPlacement(AdChoicesPlacement.TOP_RIGHT);
```
</CodeGroup>

By default the AdChoices icon position is set to the top right.

#### Use custom AdChoices view

The AdChoices custom view feature lets you position the AdChoices icon in a custom location. This is different from AdChoices position controls, which only allows specification of one of the four corners.
The following example demonstrates how to set a custom AdChoices view, with the AdChoices icon rendered inside the `CASChoicesView`.

<CodeGroup synchronize={true}>
```kotlin
adView.adChoicesView = adView.findViewById<CASChoicesView>(R.id.ad_choices_view)
```

```java
adView.setAdChoicesView((CASChoicesView) adView.findViewById(R.id.ad_choices_view));
```
</CodeGroup>

<Info>
Google Ads does not support `adView.setAdChoicesView`. Instead, specify the desired `AdChoicesPlacement` for the logo. Other ad sources will display their logo in your custom view.
</Info>

### Star Rating view

The rating from 0.0-5.0 that represents the average rating of the app in a store.

#### Use template view with auto populate rating value

Add `CASStarRatingView` to view hierarchy and CAS SDK populate rating value for you.

<CodeGroup synchronize={true}>
```kotlin
val starRatingView = adView.findViewById<CASStarRatingView>(R.id.ad_star_rating)
// Optionaly change space and color
starRatingView.space = spaceInPixels
starRatingView.color = Color.parseColor("#4285F4")

adView.starRatingView = starRatingView
```

```java
CASStarRatingView starRatingView = (CASStarRatingView) adView.findViewById(R.id.ad_star_rating);
// Optionaly change space and color
starRatingView.setSpace(spaceInPixels);
starRatingView.setColor(Color.parseColor("#4285F4"));

adView.setStarRatingView(starRatingView);
```
</CodeGroup>

#### Use custom view with auto populate rating value

Implement `NativeAdStarRating` interface in your custom view.

<CodeGroup synchronize={true}>
```kotlin
class CustomRatingView @JvmOverloads constructor(context: Context,attrs: AttributeSet? = null) : View(context, attrs), NativeAdStarRating {
    override fun getRating(): Double? = 5.0
    override fun setRating(value: Double?) {
        // Update star rating view
    }
}

adView.starRatingView = adView.findViewById<CustomRatingView>(R.id.ad_star_rating)
```

```java
class CustomRatingView extends View implements NativeAdStarRating {
    @Nullable  
    @Override  
    public Double getRating() {  
        return 5.0;  
    }  
      
    @Override  
    public void setRating(@Nullable Double aDouble) {  
        // Update star rating view
    }
}

adView.setStarRatingView((CustomRatingView) adView.findViewById(R.id.ad_star_rating));
```
</CodeGroup>

#### Use custom view with manual populate rating value

You need populate `nativeAd.starRating` value to custom view, for example `RatingBar` view:

<CodeGroup synchronize={true}>
```kotlin
val customRatingView = adView.findViewById<RatingBar>(R.id.ad_star_rating)
customRatingView.numStars = 5
customRatingView.stepSize = 0.5f

nativeAd.starRating?.let { rating ->
    customRatingView.rating = rating.toDouble()
}

adView.starRatingView = customRatingView
```

```java
RatingBar customRatingView = (RatingBar) adView.findViewById(R.id.ad_star_rating);
customRatingView.setNumStars(5);
customRatingView.setStepSize(0.5f);

Double rating = nativeAd.getStarRating();
if (rating != null) {
    customRatingView.setRating(rating);
}

adView.setStarRatingView(customRatingView);
```
</CodeGroup>
```

### Purchase Info

Source: https://production.docs.page/docs/android/purchase-info

```mdx

The `PurchaseInfo` class is used to report in-app purchases to CAS.AI. Along with the SDK's ad revenue tracking, this allows you to get a complete picture of a user's total value by combining ad revenue and IAP revenue in one place.
The total reported revenue is calculated as:

```
revenue = quantity * price * currency_rate
```

## Reporting a purchase
Call `CAS.reportPurchase(...)` with a `PurchaseInfo` object as soon as you've confirmed a completed transaction. This feeds IAP revenue into CAS.AI alongside your ad revenue.
For Google Play Billing, report the purchase after it has been successfully completed and verified.

### 1. Create `PurchaseInfo`
Build the object from the purchase's product ID, price, currency, and quantity.

<CodeGroup synchronize={true}>
```kotlin
val purchaseInfo = PurchaseInfo(
    productId = purchase.products[0],
    price = price,
    currency = currency,
    quantity = purchase.quantity
)
```

```java
PurchaseInfo purchaseInfo = new PurchaseInfo(
    purchase.getProducts().get(0),
    price,
    currency,
    purchase.getQuantity()
);
```
</CodeGroup>

| Parameter | Description |
| --- | --- |
| `productId` | Product identifier from the IAP provider. |
| `price` | Price of one purchased item in the selected currency. |
| `currency` | ISO 4217 currency code, for example `USD` or `EUR`. |
| `quantity` | Number of items being purchased. Must be at least `1`. |

### 2. Recommended: attach validation data
For Google Play purchases, pass the original purchase JSON and signature so CAS.AI can verify the purchase server-side.

<CodeGroup synchronize={true}>
```kotlin
purchaseInfo.setValidation(
    purchase.originalJson,
    purchase.signature
)
```

```java
purchaseInfo.setValidation(
    purchase.getOriginalJson(),
    purchase.getSignature()
);
```
</CodeGroup>

<Info>
Validation data is optional, but it is recommended when available.
</Info>

### 3. If the product is a subscription
For Google Play subscriptions (`BillingClient.ProductType.SUBS`), use `setSubsValidation` instead of `setValidation`. It additionally takes the purchase token and the subscription purchase time.

<CodeGroup synchronize={true}>
```kotlin
purchaseInfo.setSubsValidation(
    purchase.originalJson,
    purchase.signature,
    purchase.purchaseToken,
    purchase.purchaseTime
)
```

```java
purchaseInfo.setSubsValidation(
    purchase.getOriginalJson(),
    purchase.getSignature(),
    purchase.getPurchaseToken(),
    purchase.getPurchaseTime()
);
```
</CodeGroup>

<Info>
`purchaseToken` can be `null` and `purchaseTime` can be `0`: in that case, the values are taken from `originalJson`.
</Info>

### Other providers
Google Play Billing is used by default. For purchases processed by another provider, attach that provider's validation data instead. This also marks the purchase as coming from that provider.

<CodeGroup synchronize={true}>
```kotlin
// Amazon Appstore: receipt ID and user ID
purchaseInfo.setAmazonValidation(receipt.receiptId, userData.userId)
// or the full Amazon IAP Receipt JSON
purchaseInfo.setAmazonValidation(receipt.toJSON().toString())

// Xsolla: order ID and optional user ID
purchaseInfo.setXsollaValidation(orderId, userId)
```

```java
// Amazon Appstore: receipt ID and user ID
purchaseInfo.setAmazonValidation(receipt.getReceiptId(), userData.getUserId());
// or the full Amazon IAP Receipt JSON
purchaseInfo.setAmazonValidation(receipt.toJSON().toString());

// Xsolla: order ID and optional user ID
purchaseInfo.setXsollaValidation(orderId, userId);
```
</CodeGroup>

<Note>
For Amazon Appstore purchases, you are responsible for supplying the price, currency, and quantity values (e.g. from your own product catalog) to ensure revenue is reported accurately.
</Note>

### 4. Report
With the purchase information prepared, `purchaseInfo` is ready to send:

<CodeGroup synchronize={true}>
```kotlin
CAS.reportPurchase(purchaseInfo)
```

```java
CAS.reportPurchase(purchaseInfo);
```
</CodeGroup>

## Automatic forwarding to Tenjin
Purchases reported through `CAS.reportPurchase(...)` can also be forwarded automatically to Tenjin Analytics, so you don't need a separate integration to get IAP revenue into Tenjin.
```

### Rewarded Ads

Source: https://production.docs.page/docs/android/rewarded-ads

```mdx

Rewarded ads let you offer users in-app items, such as continued gameplay, virtual currency, or other rewards, in exchange for their engagement with ads. 
Rewarded ads boost engagement because users receive a tangible benefit for their time.

Below is a diagram showing the ad lifecycle.
<Image zoom src="/assets/Lifecycle-Rewarded-Ad.png" alt="Diagram" height="500" />


## Create Ad instance
Ad instance can be initialized along with the activity before `onCreate`.

<CodeGroup synchronize="true">
```kotlin
import com.cleveradssolutions.sdk.screen.CASRewarded

class MyActivity : Activity() {

    private val rewardedAd = CASRewarded(MyApplication.CAS_ID)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ...
    }
}
```

```java
import com.cleveradssolutions.sdk.screen.CASRewarded;

class MyActivity extends Activity {

    final CASRewarded rewardedAd = new CASRewarded(MyApplication.CAS_ID);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ...
    }
}
```
</CodeGroup>

The SDK provides the capability to create and precache multiple ad instances, enabling uninterrupted sequential ad display. CAS SDK will load mediation ads in order for each created instance.

## Create Ad Content callback

The `com.cleveradssolutions.sdk.screen.ScreenAdContentCallback` handles events related to displaying your `CASRewarded`. Callbacks are called on the main thread. Before showing ad, make sure to set `contentCallback`.

<CodeGroup synchronize="true">
```kotlin
val adContentCallback = object : ScreenAdContentCallback {
    override fun onAdLoaded(ad: AdContentInfo) {
    // (Optional) Called when the ad content has been successfully loaded.
    }


    override fun onAdFailedToLoad(format: AdFormat, error: AdError) {
        // (Optional) Called when the ad content fails to load.
    }

    override fun onAdFailedToShow(format: AdFormat, error: AdError) {
        // (Optional) Called when the ad content fails to show.
    }

    override fun onAdShowed(ad: AdContentInfo) {
        // (Optional) Called when the ad content is successfully shown.
    }

    override fun onAdClicked(ad: AdContentInfo) {
        // (Optional) Called when the ad content is clicked by the user.
    }

    override fun onAdDismissed(ad: AdContentInfo) {
        // (Optional) Called when the ad content is dismissed.
    }
}
```

```java
final ScreenAdContentCallback adContentCallback = new ScreenAdContentCallback() {  
    @Override  
    public void onAdLoaded(@NonNull AdContentInfo ad) {  
        // (Optional) Called when the ad content has been successfully loaded.  
    }  
  
    @Override  
    public void onAdFailedToLoad(@NonNull AdFormat format, @NonNull AdError error) {  
        // (Optional) Called when the ad content fails to load.  
    }  
  
    @Override  
    public void onAdFailedToShow(@NonNull AdFormat format, @NonNull AdError error) {  
        // (Optional) Called when the ad content fails to show.  
    }  
  
    @Override  
    public void onAdShowed(@NonNull AdContentInfo ad) {  
        // (Optional) Called when the ad content is successfully shown.  
    }  
  
    @Override  
    public void onAdClicked(@NonNull AdContentInfo ad) {  
        // (Optional) Called when the ad content is clicked by the user.  
    }  
  
    @Override  
    public void onAdDismissed(@NonNull AdContentInfo ad) {  
        // (Optional) Called when the ad content is dismissed.  
    }  
};
```
</CodeGroup>

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](android/impression-level-data).
- Attempting to load a new ad from the `onAdFailedToLoad()` method is strongly discouraged. Limit ad load retries to avoid continuous failed ad requests in situations such as limited network connectivity.
- When an error occurs during ad impression, executed the `onAdFailedToShow` only. In this case the `onAdDismissed` will not be executed, since the impression is not considered successful.
</Info>

## Load Ad

The next step is to fill out the `load()` method and handle the ad load callbacks. 

<CodeGroup synchronize="true">
```kotlin
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    rewardedAd.contentCallback = adContentCallback
    rewardedAd.load(this)
}
```

```java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    rewardedAd.setContentCallback(adContentCallback);
    rewardedAd.load(this);
}
```
</CodeGroup>

You can use ad load calls to build up a cache of preloaded ads before you intend to show them, so that ads can be shown with zero latency when needed. Since ads expire after an hour, you should clear this cache and reload with new ads every hour.

### Autoload mode

If enabled, the ad will automatically load new content when the current ad is dismissed or completed. Additionally, it will automatically retry loading the ad if an error occurs during the loading process.

<CodeGroup synchronize="true">
```kotlin
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    rewardedAd.contentCallback = adContentCallback
    rewardedAd.isAutoloadEnabled = true
}
```

```java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    rewardedAd.setContentCallback(adContentCallback);
    rewardedAd.setAutoloadEnabled(true);
}
```
</CodeGroup>

By default autoload disabled.

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements.

The placement name should be set before showing the ads. Maximum 100 characters allowed for the placement name.

<CodeGroup synchronize="true">
```kotlin
rewardedAd.placement = "BestPlace"
```

```java
rewardedAd.setPlacement("BestPlace")
```
</CodeGroup>

## Show Ad

When you show a rewarded ad, you will use an `OnRewardEarnedListener` object to handle reward for the user.

<CodeGroup synchronize="true">
```kotlin
import com.cleveradssolutions.sdk.screen.OnRewardEarnedListener

rewardedAd.show(this, object : OnRewardEarnedListener {
    override fun onUserEarnedReward(ad: AdContentInfo) {
    // Called when a user earns a reward from the ad.
    // TODO: Reward the user
    }
})
```

```java
import com.cleveradssolutions.sdk.screen.OnRewardEarnedListener;

rewardedAd.show(MyActivity.this, new OnRewardEarnedListener() {  
    @Override  
    public void onUserEarnedReward(@NonNull AdContentInfo ad) {  
        // Called when a user earns a reward from the ad.
        // TODO: Reward the user
    }  
});
```
</CodeGroup>

Starting with CAS SDK version 4.3.0, all ads functions can be safely called from any thread.

### Checking Ad Availability

Use `isLoaded()` to check whether an ad is currently loaded. 

<CodeGroup synchronize="true">
```kotlin
if (rewardedAd.isLoaded) {
}
```

```java
if (rewardedAd.isLoaded()) {
}
```
</CodeGroup>

Even if `isLoaded()` returns `true`, it does not guarantee that the ad will be shown successfully — various issues may still prevent it from being displayed. We strongly recommend handling potential display failures via `onAdFailedToShow(error)` callback to ensure a smoother user experience.

By relying on these callbacks, you ensure that your application can react appropriately to real-time conditions, rather than making assumptions based on ad load state at a single point in time.

## Extra fill Interstitial Ad

Controls whether interstitial ads are shown as a fallback when a rewarded video ad has no available fill. Interstitial ads do not require the user to watch the entire ad to completion. However, the `OnRewardEarnedListener` will still be triggered as if the user completed the rewarded video.
This option is enabled by default. You can disable extra fill by following line: 

<CodeGroup synchronize="true">
```kotlin
rewardedAd.isExtraFillInterstitialAdEnabled = false
```

```java
rewardedAd.setExtraFillInterstitialAdEnabled(false);
```
</CodeGroup>

## Mute Ad sounds

Indicates if the application’s audio is muted. Affects initial mute state for all ads.
Use this method only if your application has its own volume controls. 

<CodeGroup synchronize="true">
```kotlin
CAS.settings.mutedAdSounds = true
```

```java
CAS.getSettings().setMutedAdSounds(true);
```
</CodeGroup>

## Release ad resource

It is important to `destroy()` loaded but not displayed ads. 

<CodeGroup synchronize="true">
```kotlin
override fun onDestroy() {
    rewardedAd.destroy()
    super.onDestroy()
}
```

```java
@Override  
protected void onDestroy() {  
    rewardedAd.destroy();  
    super.onDestroy();  
}
```
</CodeGroup>

## Samples
- [Kotlin Rewarded Ad Activity](https://github.com/cleveradssolutions/CAS-Android/blob/master/kotlinSample/src/main/java/com/cleveradssolutions/sampleapp/rewarded/RewardedAdActivity.kt)
- [Java Rewarded Ad Activity](https://github.com/cleveradssolutions/CAS-Android/blob/master/javaSample/src/main/java/com/cleveradssolutions/sampleapp/rewarded/RewardedAdActivity.java)
```

### Targeting options

Source: https://production.docs.page/docs/android/targeting-options

```mdx

You can now easily tailor the way you serve your ads to fit a specific audience!  
You’ll need to inform our servers of the users’ details so the SDK will know to serve ads according
to the segment the user belongs to.

### User ID
The userID is a unique identifier supplied by your application and must be static for each user across sessions.

<CodeGroup synchronize={true}>
```kotlin
CAS.targetingOptions.userID = "user-hash-code"
```

```java
CAS.getTargetingOptions().setUserID("user-hash-code");
```
</CodeGroup>

<Warning>  
Your userID should not contain any personally identifiable information such as  an email address, screen name, Android ID (AID), or Google Advertising ID (GAID).
</Warning>

### User Age

Set user age. Limitation: 1-99. By default 0 is 'unknown'.

<CodeGroup synchronize={true}>
```kotlin
CAS.targetingOptions.age = 12
```

```java
CAS.getTargetingOptions().setAge(12);
```
</CodeGroup>

### User Gender

Set targeting to user’s gender. Limitation: `GENDER_UNKNOWN, GENDER_MALE, GENDER_FEMALE`.

<CodeGroup synchronize={true}>
```kotlin
CAS.targetingOptions.gender = TargetingOptions.GENDER_MALE
```

```java
CAS.getTargetingOptions().setGender(TargetingOptions.GENDER_MALE);
```
</CodeGroup>

### User Location

Set the user's current location. Location data is not used to CAS; however, it may be used by third party ad networks.

<CodeGroup synchronize={true}>
```kotlin
CAS.targetingOptions.location = userLocation
```

```java
CAS.getTargetingOptions().setLocation(userLocation);
```
</CodeGroup>

<Warning>  
Do not use Location just for advertising. Your app should have a valid use case for it as well.
</Warning>

### User Location auto collection

Collect from the device the latitude and longitude coordinated truncated to the hundredths decimal place.

* Collect only if your application already has the relevant end-user permissions.
- Does not collect if the target audience is children.
- Disabled by default.

<CodeGroup synchronize={true}>
```kotlin
CAS.targetingOptions.locationCollectionEnabled = true
```

```java
CAS.getTargetingOptions().setLocationCollectionEnabled(true);
```
</CodeGroup>

### App Keywords

Set a list of keywords, interests, or intents related to your application. Words or phrases describe
the current activity of the user for targeting purposes.

<CodeGroup synchronize={true}>
```kotlin
CAS.targetingOptions.keywords = setOf("sports", "football", "fitness")
```

```java
CAS.getTargetingOptions().setKeywords(
    new java.util.HashSet<>(java.util.Arrays.asList("sports", "football", "fitness"))
);
```
</CodeGroup>

### App Content URL

Set the content URL for a website whose content matches the app's primary content. This website content is used for targeting and brand safety purposes. Limitation: max URL length 512.

<CodeGroup synchronize={true}>
```kotlin
CAS.targetingOptions.contentUrl = contentUrl
```

```java
CAS.getTargetingOptions().setContentUrl(contentUrl);
```
</CodeGroup>
```

### User Consent Flow

Source: https://production.docs.page/docs/android/user-consent-flow

```mdx

<Info>
It is optional to use the CMP flow included with the CAS SDK. If you integrate your own CMP flow, make sure that flow completes before you initialize the CAS SDK.
</Info>

<Info>
If you implement a CMP that is compliant with IAB TCF v2 ([Transparency & Consent Framework](https://iabeurope.eu/tcf-2-0/)) for your user consent flow, the CAS SDK supports sending the TCF v2 consent to networks. In this case, the CAS Consent Flow will not be shown to the user.
</Info>

In order for CAS and our ad providers to deliver ads that are more relevant to your users, as a mobile app publisher, you need to collect explicit user consent for use of personal data in the regions covered by GDPR, CCPA, LGPD, PIPEDA.

Keep in mind that it’s best to contact qualified legal professionals, if you haven’t done so already, to get more information and be well-prepared for compliance.  

Read more about:
- GDPR - [General Data Protection Regulation](https://gdpr-info.eu)
- CCPA - [The California Consumer Privacy Act](https://theccpa.org)
- LGPD - [General Personal Data Protection Act](https://lgpd-brazil.info)
- PIPEDA - [The Personal Information Protection and Electronic Documents Act](https://www.priv.gc.ca/en/privacy-topics/privacy-laws-in-canada/the-personal-information-protection-and-electronic-documents-act-pipeda/)

<Image height="400" alt="image" src="/assets/User-Consent-Flow-1.png" />

#### Users will not see the Consent dialog if at least one of following is true
- Users located in regions that are not covered by information protection
- Users who are subject to COPPA restrictions.

## Automatic consent flow
The automatic consent flow is enabled by default and described on the [CAS initialization page](android/initialize-cas).

## Manual consent flow
Call `showIfRequired()` on the `ConsentFlow` class. If the consent is required, the SDK loads a form and immediately presents it . 
The `OnDismissListener` is called after the form is dismissed. If consent is not required, the `OnDismissListener` is called immediately.
<CodeGroup synchronize={true}>
```kotlin
ConsentFlow()
    .withDismissListener(object : ConsentFlow.OnDismissListener {
        override fun onConsentFlowDismissed(status: Int) {
            if (status == ConsentFlow.Status.OBTAINED) {
                // User consent obtained
            }
        }
    })
    .showIfRequired()
```

```java
new ConsentFlow()
    .withDismissListener(new ConsentFlow.OnDismissListener() {  
        @Override  
        public void onConsentFlowDismissed(int status) {  
            if (status == ConsentFlow.Status.OBTAINED) {
                // User consent obtained
            }
        }  
    })
    .showIfRequired();
```

</CodeGroup>

<Warning>  
The `show()` and `showIfRequired()` methods must be called from the main (UI) thread.
</Warning>

| ConsentFlow.Status | Description                                                        |
| ------------------ | ------------------------------------------------------------------ |
| OBTAINED           | User consent obtained. Personalized vs non-personalized undefined. |
| NOT_REQUIRED       | User consent not required.                                         |
| UNAVAILABLE        | User consent unavailable.                                          |
| INTERNAL_ERROR     | There was an internal error.                                       |
| NETWORK_ERROR      | There was an error loading data from the network.                  |
| CONTEXT_INVALID    | There was an error with the UI context is passed in.               |
| FLOW_STILL_SHOWING | There was an error with another form is still being displayed.     |

<Warning>  
The cache consent status on your app or a previously saved consent string, could lead to a [TCF 3.3](https://support.google.com/admanager/answer/9999955) error if consent is expired.
</Warning>

## Privacy options button

Some consent forms require the user to modify their consent at any time. Adhere to the following steps to implement a privacy options button if required.

1. Implement a UI element, such as a button in your app's settings page, that can trigger a privacy options form.
2. Once `showIfRequired()` completes, check `isConsentObtained` to determine whether to display the UI element that can present the privacy options form.
3. When a user interacts with your UI element, call `show()` to show the form so the user can update their privacy options at any time.

<CodeGroup synchronize={true}>
```kotlin
class MyActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // ...

        initializeCAS()
        generateOptionsMenu(ConsentFlow.Status.OBTAINED)
    }

    private fun initializeCAS() {
        val builder = CAS.buildManager()
            .withCasId(MyApplication.CAS_ID)
            .withTestAdMode(BuildConfig.DEBUG)
            .withCompletionListener(object : InitializationListener {
                override fun onCASInitialized(config: InitialConfiguration) {
                    // The user completes the consent flow
                    generateOptionsMenu(config.consentFlowStatus)
                }
            })

        builder.build(this)
    }

    private fun generateOptionsMenu(status: Int) {
        if (status == ConsentFlow.Status.OBTAINED) {
            // Generate the options menu to include the privacy button.
        } else {
            // Regenerate the options menu to remove the privacy button.
        }
    }

    fun showPrivacyOptionsForm() {
        ConsentFlow()
            .withDismissListener(object : ConsentFlow.OnDismissListener {
                override fun onConsentFlowDismissed(status: Int) {
                    generateOptionsMenu(status)
                }
            })
            .withUIContext(this)
            .show()
    }
}
```

```java
class MyActivity extends Activity {

    @Override  
    protected void onCreate(@Nullable Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);
        ...
        
        initializeCAS();
        generateOptionsMenu(ConsentFlow.Status.OBTAINED);
    }
    
    void initializeCAS() {
        ManagerBuilder builder = CAS.buildManager()
            .withCasId(MyApplication.CAS_ID)
            .withTestAdMode(BuildConfig.DEBUG)
            .withCompletionListener(new InitializationListener() {  
                @Override  
                public void onCASInitialized(@NonNull InitialConfiguration config) {  
                    // The user completes the consent flow
                    generateOptionsMenu(config.getConsentFlowStatus());
                }  
            });
    
        builder.build(this);
    }
    
    void generateOptionsMenu(int status) {
        if (status == ConsentFlow.Status.OBTAINED) {
            // Generate the options menu to include the privacy button.
        } else {
            // Regenerate the options menu to remove the privacy button.
        }
    }

    void showPrivacyOptionsForm() {
        new ConsentFlow()
            .withDismissListener(new ConsentFlow.OnDismissListener() {  
                @Override  
                public void onConsentFlowDismissed(int status) {  
                    generateOptionsMenu(status);
                }  
            })
            .withUIContext(activity)
            .show();
    }
}
```
</CodeGroup>

## Debug geography

The SDK provides a way to test your app's behavior as though the device was located in the EEA or UK using the `WithDebugGeography` option. 

<CodeGroup synchronize={true}>
```kotlin
ConsentFlow()
    .withDebugGeography(ConsentFlow.DebugGeography.EEA)
    .withForceTesting(BuildConfig.DEBUG)
    .showIfRequired()
```

```java
new ConsentFlow()
    .WithDebugGeography(ConsentFlow.DebugGeography.EEA)
    .withForceTesting(BuildConfig.DEBUG)
    .ShowIfRequired();
```
</CodeGroup>

<Info>
Note that debug geography only work if:
- Active test device defined in `CAS.settings.testDeviceIds`.
- `withForceTesting` value is true.
</Info>

## Meta Audience Network Data Processing Options for Users in California

The CAS does not support your handling of CCPA opt-out values for Meta Audience Network, you must work directly with the network to  purposes of your obligations for CCPA compliance.

To learn how to implement Meta Audience Network’s “Limited Data Use” flag, read the [Additional Meta AudienceNetwork steps](android/additional-meta-audiencenetwork-steps).

## Custom Consent Logic

The following instructions apply if you are using your own or a third-party party consent mechanism.

<Error>  
If you access Google demand through CAS, it’s critical that you review the [Google CMP requirements](https://support.google.com/adsense/answer/13554116) before you start the integration process.
</Error>

<Warning>  
You must set the privacy options before initialize the CAS to disable the automatic CAS consent flow and advertising SDKs are initialized respecting the user's consent.
</Warning>

### Consent in GDPR and Other regions

CAS shares these set consent values via adapters to supported mediation partners.

If the user consents to interest-based advertising, set the user consent `ACCEPTED` flag: 

<CodeGroup synchronize={true}>
```kotlin
CAS.settings.setUserConsent(ConsentStatus.ACCEPTED)
```

```java
CAS.getSettings().setUserConsent(ConsentStatus.ACCEPTED);
```
</CodeGroup>

If the user does NOT consent to interest-based advertising, set the user consent `DENIED` flag:

<CodeGroup synchronize={true}>
```kotlin
CAS.settings.setUserConsent(ConsentStatus.DENIED)
```

```java
CAS.getSettings().setUserConsent(ConsentStatus.DENIED);
```
</CodeGroup>

Once you set the consent value, CAS will continue to respect that value for the lifetime of your application or until the user consents to interest-based advertising.

### Multi-State Consumer privacy laws

California and Virginia laws may require you to display a “Do Not Sell or Share My Personal Information” link or provide other options to users located in those states to opt out of interest-based advertising. You must set a flag that indicates whether users in those states opt out of interest-based advertising or the sale or share of personal information for interest-based advertising.

If a user does NOT opt out of interest-based advertising, set the `OPT_IN_SALE` flag: 

<CodeGroup synchronize={true}>
```kotlin
CAS.settings.setCcpaStatus(CCPAStatus.OPT_IN_SALE)
```

```java
CAS.getSettings().setCcpaStatus(CCPAStatus.OPT_IN_SALE);
```
</CodeGroup>

If a user does opt out of interest-based advertising, set the `OPT_OUT_SALE` flag:

<CodeGroup synchronize={true}>
```kotlin
CAS.settings.setCcpaStatus(CCPAStatus.OPT_OUT_SALE)
```

```java
CAS.getSettings().setCcpaStatus(CCPAStatus.OPT_OUT_SALE);
```
</CodeGroup>

You do not need to set this flag for users who are outside California. If you do set this flag for such users, this will not impact how ads are served to them.
```

### App Open Ads

Source: https://production.docs.page/docs/construct/app-open-ads

```mdx

App open ads are a special ad format intended for publishers wishing to monetize their app load screens.
App open ads can be closed at any time, and are designed to be shown when your users bring your app to the foreground.
App open ads automatically show a small branding area so users know they're in your app.

## Load AppOpen ad
Loads an AppOpen ad. This action works asynchronously, and you can use the `Wait for previous actions to complete` action to wait until the ad has been loaded or failed to load.

When autoload is enabled, a new ad will be automatically loaded after each display, and loading failures will trigger automatic retry attempts.

Ad content may take some time to load after creating an ad instance.
To ensure the ad displays instantly when needed, load the ad instance in advance.

### Conditions
- On AppOpen Ad Loaded: Triggered when an app open ad is successfully loaded.
- On AppOpen Ad Failed to Load: Triggered when an app open ad fails to load.
- Is AppOpen Ad Loaded: Checks if an app open ad is loaded.


## Show AppOpen ad
App open ads help you monetize your app's loading screen, when the app first launches and during app switches, but it's important to keep best practices in mind so that your users enjoy using your app. It's best to:
* Show your first app open ad after your users have used your app a few times.
* Show app open ads during times when your users would otherwise be waiting for your app to load.
* If a user returns to your app after having left it by clicking on an app open ad, make sure they're not presented with another app open ad immediately.

This action works asynchronously, and you can use the `Wait for previous actions to complete` action to wait until the ad has been dismissed or failed to show.

### Conditions
- On AppOpen Ad Failed to Show: Triggered when an app open ad fails to show.
- On AppOpen Ad Showed: Triggered when an app open ad is shown.
- On AppOpen Ad Clicked: Triggered when an app open ad is clicked.
- On AppOpen Ad Dismissed: Triggered when an app open ad is dismissed.

There is no need to check whether the ad is loaded before showing it. If the ad is not ready at that moment, the `On ad failed to show` condition will be triggered.

<Info>
When an error occurs during ad impression, only the `On ad failed to show` condition is triggered.  
In this case, the `On ad dismissed` condition will not be fired since the impression is not considered successful.
</Info>

## Destroy AppOpen ad
Destroys the app open ad instance and frees up resources. To resume working with ads, use the load ad action.

## Cold starts and Loading screens

There is a delay between when you request an ad and when you receive an ad to show.
If you do not design your app well, the user may briefly see your app and then be surprised by an out-of-context ad.
Prevent this bad user experience. You can handle cold starts by showing a loading screen before any app content, and then showing the ad after the loading screen.
If your app shows any app content after the loading screen, do not show the ad.

## Best Practices

* When an app open ad is not yet loaded (i.e. on cold start), load it first. Load any other ad formats later so that you avoid loading them in parallel with the app open ad. Loading multiple ad formats in parallel is not good for the device’s resources or for ad demand SDKs.
* If you have a loading screen under the app open ad, and your loading screen completes loading before the ad is dismissed, you may want to dismiss your loading screen in the `On ad dismissed` and `On ad failed to show` document event listeners.
* Wait a variable number of days after initial install to show on cold start.
* Only show an ad if the user backgrounds the app for a certain amount of time (i.e. 30 seconds).
* If you show a cold start ad, do not show soft launch app open ads or interstitials for a certain amount of time.
* Include a call-out to the user that tells them they will see an ad in the Splash/Loading screen. For example: “Watch an ad from our sponsor while the app loads.”
```

### Automation options

Source: https://production.docs.page/docs/construct/automation-options

```mdx

## Consent Flow Auto show if required
To collect user consent for personal data, use the built-in **Consent Flow**. It shows a consent form automatically during startup.

## Banner Ad Auto load
Automatically loads ads retry loading the ad if an error occurs during the loading process.

<Warning>
Unlike other formats, for automatic loading to work you need to trigger banner ad loading at least once and specify the required size.
</Warning>

## Banner Ad Auto Refresh
Interval (in seconds) for refreshing banner ads. Once elapsed, a new ad automatically loads and displays. Set 0 to disable auto refresh ad.

## MREC Ad Auto load
Automatically loads ads on startup and retry loading the ad if an error occurs during the loading process.

## MREC Ad Auto Refresh
Interval (in seconds) for refreshing banner ads. Once elapsed, a new ad automatically loads and displays. Set 0 to disable auto refresh ad.

## AppOpen Ad Auto load
Automatically loads ads on startup and after they are shown and retries on load errors.

## AppOpen Ad Auto Show
Automatically show ads when the user resumes a previously launched app. This automation does not mean the ad will be shown immediately upon loading.

## Interstitial Ad Auto load
Automatically loads ads on startup and after they are shown and retries on load errors.

## Interstitial Ad Auto Show
Automatically show ads when the user resumes a previously launched app. This automation does not mean the ad will be shown immediately upon loading.

## Interstitials Ad Min Interval
Minimum time (in seconds) required between interstitial ad displays.

## Rewarded Ad Auto load
Automatically loads ads on startup and after they are shown and retries on load errors.

## Collect Location
Collect from the device the latitude and longitude coordinated truncated to the hundredths decimal place.

Collect only if your application already has the relevant end-user permissions.
- Does not collect if the target audience is children.
- Disabled by default.

## (Optional) Trial ad-free interval
Defines the time interval, in seconds, starting from the moment of the initial app installation, during which users can use the application without ads being displayed while still retaining access to the Rewarded Ads format. Within this interval, users enjoy privileged access to the application's features without intrusive advertisements.
```

### Banner Ads

Source: https://production.docs.page/docs/construct/banner-ads

```mdx

Banner Ad units display rectangular ads that occupy a portion of an app's layout.
They can refresh automatically after a set period of time.
This means users view a new ad at regular intervals, even if they stay on the same screen in your app.
They're also the simplest ad format to implement.

# Update soon...

```json
{
  "load-banner-ad": {
    "list-name": "Load Banner Ad",
    "display-text": "Load [i]{0}[/i] banner ad with limits ([i]{1}[/i], [i]{2}[/i])",
    "description": "Loads a banner ad with specified size. [b]The ad will not be displayed on the screen until the show action is performed.[/b] This action works asynchronously, and you can use the 'Wait for previous actions to complete' action to wait until the ad has been loaded or failed to load.",
    "params": {
      "ad-size": {
        "name": "Ad Size",
        "desc": "The size of the banner ad. The banner can only have one ad size at a time. Calling the load action with a different size will destroy the loaded ad and load a new one with the requested size.",
        "items": {
          "adaptive": "Adaptive",
          "inline": "Inline",
          "smart": "Smart",
          "leaderboard": "Leaderboard",
          "standard": "Standard"
        }
      },
      "max-width": {
        "name": "Max Width",
        "desc": "The maximum width of the banner ad in DP. Leave 0 to not limit. Used to limit Adaptive and Inline banners only."
      },
      "max-height": {
        "name": "Max Height",
        "desc": "The maximum height of the banner ad in DP. Leave 0 to not limit. Used to limit Inline banners only."
      }
    }
  },
  "show-banner-ad": {
    "list-name": "Show Banner Ad",
    "display-text": "Show banner ad at [i]{0}[/i] with offset ([i]{1}[/i], [i]{2}[/i])",
    "description": "Displays the banner ad at the specified position with optional offsets. The banner’s position can be changed at any time by performing this action with new parameters.",
    "params": {
      "position": {
        "name": "Position",
        "desc": "The position on the screen to display the banner ad. The CAS will not allow an ad to be placed outside the screen or overlap with screen cutouts. Some anchor positions do not support offset on the X or Y axis, this can be seen as (X, Y).",
        "items": {
          "top-center": "Top Center (Y)",
          "top-left": "Top Left (X, Y)",
          "top-right": "Top Right (X, Y)",
          "bottom-center": "Bottom Center (-)",
          "bottom-left": "Bottom Left (X)",
          "bottom-right": "Bottom Right (X)",
          "middle-center": "Middle Center (Y)",
          "middle-left": "Middle Left (X, Y)",
          "middle-right": "Middle Right (X, Y)"
        }
      },
      "x-offset": {
        "name": "X Offset",
        "desc": "The horizontal offset from the specified position in DP. Leave 0 to not use offset."
      },
      "y-offset": {
        "name": "Y Offset",
        "desc": "The vertical offset from the specified position in DP. Leave 0 to not use offset."
      }
    }
  },
  "hide-banner-ad": {
    "list-name": "Hide Banner Ad",
    "display-text": "Hide banner ad",
    "description": "Hides the currently displayed banner ad."
  },
  "destroy-banner-ad": {
    "list-name": "Destroy Banner Ad",
    "display-text": "Destroy banner ad",
    "description": "Destroys the banner ad instance and frees up resources. To resume working with ads, use the load ad action."
  },
}
```

## Load Banner ad
Loads an Banner ad. This action works asynchronously, and you can use the `Wait for previous actions to complete` action to wait until the ad has been loaded or failed to load.


When autoload is enabled, a loading failures will trigger automatic retry attempts.

Ad content may take some time to load after creating an ad instance.
To ensure the ad displays instantly when needed, load the ad instance in advance.

### Ad size
To load a banner ad, you need to specify the ad size. The banner can only have one ad size at a time. Calling the load action with a different size will destroy the loaded ad and load a new one with the requested size.

<Property name="Adaptive" type="AdSize">
Adaptive banner ads have a fixed aspect ratio for the maximum width. 
The adaptive size calculates the optimal height for that width with an aspect ratio similar to 320x50. By default, the full screen width will be used. You can limit width by specifying a `Max width` in the parameters.
</Property>

---

<Property name="Inline" type="AdSize">
Inline banner ads have a desired width and a maximum height, useful when you want to limit the banner's height. Inline banners are larger and taller compared to adaptive banners. They have variable height, including Medium Rectangle size, and can be as tall as the device screen. Specify the `Max width` and `Max height` dimensions to limit the ad size.
</Property>

---

<Property name="Smart" type="AdSize">
Smart selects the optimal dimensions depending on the device type. For mobile devices, it returns 320x50, while for tablets, it returns 728x90. In the UI, these banners occupy the same amount of space regardless of device type.
</Property>

---

<Property name="Leaderboard" type="AdSize">
Leaderboard has a fixed size of 728x90 and is allowed on tablets only.
</Property>

---

<Property name="Standard" type="AdSize">
Standard banner has a fixed size of 320x50 and is the minimum ad size
</Property>

---

<Property name="Max Width" type="number">
Maximum width for `Adaptive` and `Inline` banners in Density-independent Pixels(DP).  
By default, adaptive and inline banners use the full device width.  
Automatically clamped to the screen bounds and updated on orientation changes.
Leave 0 to not limit.
</Property>

---

<Property name="Max Height" type="number">
Maximum height for `Inline` banners in Density-independent Pixels(DP).
By default, inline adaptive banners use the device height.
Automatically clamped to the screen bounds and updated on orientation changes.
Leave 0 to not limit.
</Property>

## Conditions
- On Banner Ad Loaded: Triggered when an Banner ad is successfully loaded.
- On Banner Ad Failed to Load: Triggered when an Banner ad fails to load.
- On Banner Ad Clicked: Triggered when an Banner ad is clicked.
- Is Banner Ad Loaded: Checks if an Banner ad is loaded.

## Show Banner ad
The banner will not be visible until **show** action is performed. The show function has a position parameter that specifies where the banner ad should be placed.

To change the banner’s position on the screen, simply perform the show action again with the new parameters.

The banner's activity can be changed even if it is not ready to be shown yet. When the ad becomes ready, it will be shown automatically if autoload/show logic requires it.

### Ad Position
The `X offset` and `Y offset` properties allow you to adjust the banner’s position relative to the specified anchor position, in DP. CAS will not allow an ad to be placed outside the screen or overlap with screen cutouts. Leave 0 to not use offset.

Some anchor positions do not support offset on the X or Y axis, this can be seen in the table as (X, Y).

|        | Left     | Center |    Right |
| ------ | -------- | :----: | -------: |
| Top    | TL(X, Y) | TC(Y)  | TR(X, Y) |
| Middle | ML(X)    | MC(-)  |    MR(X) |
| Bottom | BL(X, Y) | BC(Y)  | BR(X, Y) |

The coordinates on the screen are determined in Density-independent Pixels(DP).

## Hide Banner Ad
Hides the currently displayed Banner ad.

## Destroy Banner ad
Destroys the Banner ad instance and frees up resources. To resume working with ads, use the load ad action.
```

### Build Construct app for Mobile platforms

Source: https://production.docs.page/docs/construct/build

```mdx


Construct 3 has its own mobile app build service. For most users this is the recommended way to build mobile apps. However there are limits on which third-party Cordova plugins can be used, and the build involves uploading your project and downloading an APK, which can be slow with large projects or slow connections. Using the Cordova CLI allows offline builds and use of any third-party Cordova plugins.

## Construct Build Service
Construct 3 Build Service uses an allowlist system for Cordova plugins, so only explicitly allowed plugins can be used. The CAS.AI add-on depends on [cordova-plugin-cas-ai](https://www.npmjs.com/package/cordova-plugin-casai).
> [Original Construct topic](https://www.construct.net/en/forum/construct-3/plugin-sdk-10/build-server-cordova-plugin-149266)

We submit each `cordova-plugin-cas-ai` update for whitelisting in the Construct Build Service, but reviews by the Construct support team can take up to a week.

The latest CAS.AI plugin versions may not yet be available in the Construct Build Service. Consider using the [Cordova CLI](https://cleveradssolutions.docs.page/docs/construct/build) to build your application in the meantime. 

Follow [this issue](https://github.com/cleveradssolutions/CAS-Construct/issues/2) to track currently available versions.

<Warning>
If you attempt to build your application with a plugin version that has not been whitelisted, our Cordova plugin will not be included in your build with no errors shown. The issue will only become visible when running on a device.
</Warning>

> [Original Build App in Construct topic](https://www.construct.net/en/tutorials/publish-mobile-apps-26) 

## Cordova CLI
To set up the Cordova CLI on your computer, you'll first need to install [Node.js](https://nodejs.org). Then install the cordova module using npm. For Windows, use the command:
```sh
npm install -g cordova
```
On macOS or Linux use the command:
```sh
sudo npm install -g cordova
```
For more information, see the section Installing the Cordova CLI in the [Cordova documentation](https://cordova.apache.org/docs/en/latest/guide/cli/index.html).

At this point you should be able to enter the command cordova in a command prompt or terminal, and see that it prints help text about using Cordova.

<Tabs groupId="platform">
<TabItem label="Android setup" value="android">
For Android builds, you'll need to install the [JDK (Java Development Kit)](https://www.oracle.com/java/technologies/downloads/) and [Android Studio](https://www.construct.net/out?u=https%3a%2f%2fdeveloper.android.com%2fstudio). For more information see the [Cordova Android Platform Guide](https://cordova.apache.org/docs/en/latest/guide/platforms/android/index.html).

</TabItem>
<TabItem label="iOS setup" value="ios">
For iOS builds you'll need to install Xcode from the App Store, as well as the ios-deploy npm module via
```sh
npm install -g ios-deploy
``` 

For more information see the [Cordova iOS Platform Guide](https://cordova.apache.org/docs/en/latest/guide/platforms/ios/index.html).

<Info>
Note that iOS apps must be built on a Mac. You can get as far as generating an Xcode project on a Windows or Linux machine, but you must move to a Mac to finish the build.
</Info>

<Warning>
Required minimum Xcode version `{{ min.xcode }}`.
</Warning>

</TabItem>
</Tabs>

### Exporting from Construct
In Construct 3, choose the Android (Cordova) or iOS (Cordova) options when exporting, depending on which platform you want to build for.

In the Cordova options dialog, choose **Cordova project** for Android build or iOS build. Construct 3 will export a zip file. Extract this zip file to a folder on your computer.

- Set Minimum Android API level `{{ min.api }}` or higher.
- Set Minimum Target iOS version `{{ min.ios }}` or higher

### Preparing Cordova project
By now you should have a folder with `config.xml` in it (and possibly some other files), and a `www` subfolder. 

Open a command prompt with the current directory set to the location `config.xml` is in. 
Use the following command to prepare a full Cordova project based on the exported files:
```sh
cordova prepare
```

This may take a while as it fetches dependencies and configures the project.

Once it's done, if this is your first build, you might want to check you have the right software installed. You can do this with:
```sh
cordova requirements
```

Cordova will then tell you if it has everything it needs. If anything is missing you might have to go back and install something else. Cordova should provide instructions if so.

### Building apps
To build the app, simply use:
```sh
cordova build
```
```

### Development Options

Source: https://production.docs.page/docs/construct/development-options

```mdx

It's important to enable test ads during development so that you can click on them without charging CAS advertisers.

<Error>  
We strongly suggest that you enable test ads mode when you validate the integration. If you click on too many ads without being in test mode, you risk your account being flagged for invalid activity.  
</Error>  

There are two ways to get test ads:
- [Enable test ad mode](construct/development-options#force-test-ads) for all devices.
- [Set device ids to test ad](construct/development-options#test-device-ids).

Ads with Test Ads mode are safe to click. Requests, impressions, and clicks on test ads will not show up in your account's reports.
Test full-screen ads displays details of CAS integration and tips for solving errors. Go to the Mediation Adapters section to make sure that the advertising networks you want are integrated correctly.

<Image height="500" alt="image" src="/assets/Enabling-test-ads-1.jpg" />  
<Image height="500" alt="image" src="/assets/Enabling-test-ads-2.jpg" />  

## Force Test ads
The quickest way to enable testing is to use test ad mode. The test ad mode are not associated with your CAS account, so there's no risk of your account generating invalid traffic when using these test ad mode.
The easiest way to load test ads is to use:

## Test device IDs
If you want to do more rigorous testing with production-looking ads, you can now configure your device as a test device and use your own manager id. Test devices can either be added programmatically.

Follow the steps below to add your device as a test device.

1. Run an app configured with the CAS on device.
2. Check the logcat output for a message that looks like this:

```
To get test ads on this device, set "12345678901234567890123456789012"
```

3. Copy your alphanumeric test device ID to your clipboard.
4. Add device ID to CAS object properties, separated `,`.
  - Development Options  
    Test Device IDs: `12345678901234567890123456789012,12345678901234567890123456789012`

5. Re-run your app.
6. Well done, ads on this device are safe to click. Requests, impressions, and clicks on ads in test mode will not show up in your account's reports.

## Debug Logging
The enabled Debug Mode will display a lot of useful information for debugging about the states of the SDK with log tag `CAS.AI`. Disabling Debug Mode may improve application performance.

<Info>  
If you have discovered the problem in the work of the SDK, please provide us with a description of the problem along with the full log of your device.  
</Info>  

## Debug Geography
The CAS provides a way to test your app's behavior as though the device was located in the EEA or UK using the Debug Geography.
Select debug geography, and the setting will be applied only for test sessions.

- `Unknown` - Geography is unknown.
- `European Economic Area` - Geography appears as in the European Economic Area.
- `US State` - Geography appears as in a regulated US State.
- `Unregulated` - Geography appears as in a region with no regulation.
```

### Interstitial Ads

Source: https://production.docs.page/docs/construct/interstitial-ads

```mdx

Interstitial ads are full-screen ads that cover the interface of their host app.
They're typically displayed at natural transition points in the flow of an app, such as between screens.
When an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.


## Load Interstitial ad
Loads an Interstitial ad. This action works asynchronously, and you can use the `Wait for previous actions to complete` action to wait until the ad has been loaded or failed to load.

When autoload is enabled, a new ad will be automatically loaded after each display, and loading failures will trigger automatic retry attempts.

Ad content may take some time to load after creating an ad instance.
To ensure the ad displays instantly when needed, load the ad instance in advance.

### Conditions
- On Interstitial Ad Loaded: Triggered when an Interstitial ad is successfully loaded.
- On Interstitial Ad Failed to Load: Triggered when an Interstitial ad fails to load.
- Is Interstitial Ad Loaded: Checks if an Interstitial ad is loaded.


## Show Interstitial ad
Interstitial ads should be displayed during natural pauses in the flow of an app. Between app screens is a good example, or after the user completes a task.

This action works asynchronously, and you can use the `Wait for previous actions to complete` action to wait until the ad has been dismissed or failed to show.

### Conditions
- On Interstitial Ad Failed to Show: Triggered when an Interstitial ad fails to show.
- On Interstitial Ad Showed: Triggered when an Interstitial ad is shown.
- On Interstitial Ad Clicked: Triggered when an Interstitial ad is clicked.
- On Interstitial Ad Dismissed: Triggered when an Interstitial ad is dismissed.

There is no need to check whether the ad is loaded before showing it. If the ad is not ready at that moment, the `On ad failed to show` condition will be triggered.

<Info>
When an error occurs during ad impression, only the `On ad failed to show` condition is triggered.  
In this case, the `On ad dismissed` condition will not be fired since the impression is not considered successful.
</Info>

## Destroy Interstitial ad
Destroys the Interstitial ad instance and frees up resources. To resume working with ads, use the load ad action.

## Some best practices

#### Consider whether interstitial ads are the right type of ad for your app.

Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, like sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it's easy to present an interstitial ad without disrupting their experience. Make sure you consider at which points in your app's workflow you'll display interstitial ads and how the user is likely to respond.

#### Remember to pause the action when displaying an interstitial ad.

There are a number of different types of interstitial ads: text, image, video, and more. It's important to make sure that when your app displays an interstitial ad, it also suspends its use of some resources to allow the ad to take advantage of them. For example, when you make the call to display an interstitial ad, be sure to pause any audio output being produced by your app.

#### Allow for adequate loading time.

Just as it's important to make sure you display interstitial ads at an appropriate time, it's also important to make sure the user doesn't have to wait for them to load. Loading the ad in advance by calling `load` before you intend to call `show` can ensure that your app has a fully loaded interstitial ad at the ready when the time comes to display one.

#### Don't flood the user with ads.

While increasing the frequency of interstitial ads in your app might seem like a great way to increase revenue, it can also degrade the user experience and lower clickthrough rates. Make sure that users aren't so frequently interrupted that they're no longer able to enjoy the use of your app.
```

### Medium Rectangle Banner Ads

Source: https://production.docs.page/docs/construct/mrec-ads

```mdx

Medium Rectangle (MREC) are rectangular image or text ads that occupy a spot with size in dp (300x250) on screen. 
They stay on screen while users are interacting with the app, and can refresh automatically after a certain period of time. 

## Load MREC ad
Loads an MREC ad. This action works asynchronously, and you can use the `Wait for previous actions to complete` action to wait until the ad has been loaded or failed to load.

When autoload is enabled, a new ad will be automatically loaded after each display, and loading failures will trigger automatic retry attempts.

Ad content may take some time to load after creating an ad instance.
To ensure the ad displays instantly when needed, load the ad instance in advance.

## Conditions
- On MREC Ad Loaded: Triggered when an MREC ad is successfully loaded.
- On MREC Ad Failed to Load: Triggered when an MREC ad fails to load.
- On MREC Ad Clicked: Triggered when an MREC ad is clicked.
- Is MREC Ad Loaded: Checks if an MREC ad is loaded.

## Show MREC ad
The banner will not be visible until `show` action is performed. The show function has a position parameter that specifies where the banner ad should be placed.

To change the banner’s position on the screen, simply perform the show action again with the new parameters.

The banner's activity can be changed even if it is not ready to be shown yet. When the ad becomes ready, it will be shown automatically if autoload/show logic requires it.

### Ad Position
The `X offset` and `Y offset` properties allow you to adjust the banner’s position relative to the specified anchor position, in DP. CAS will not allow an ad to be placed outside the screen or overlap with screen cutouts. Leave 0 to not use offset.

Some anchor positions do not support offset on the X or Y axis, this can be seen in the table as (X, Y).

|        | Left     | Center |    Right |
| ------ | -------- | :----: | -------: |
| Top    | TL(X, Y) | TC(Y)  | TR(X, Y) |
| Middle | ML(X)    | MC(-)  |    MR(X) |
| Bottom | BL(X, Y) | BC(Y)  | BR(X, Y) |

The coordinates on the screen are determined in Density-independent Pixels(DP).

## Hide MREC Ad
Hides the currently displayed MREC ad.

## Destroy MREC ad
Destroys the MREC ad instance and frees up resources. To resume working with ads, use the load ad action.
```

### Rewarded Ads

Source: https://production.docs.page/docs/construct/rewarded-ads

```mdx

Rewarded ads let you offer users in-app items, such as continued gameplay, virtual currency, or other rewards, in exchange for their engagement with ads.
Rewarded ads boost engagement because users receive a tangible benefit for their time.

## Load Rewarded ad
Loads an Rewarded ad. This action works asynchronously, and you can use the `Wait for previous actions to complete` action to wait until the ad has been loaded or failed to load.

When autoload is enabled, a new ad will be automatically loaded after each display, and loading failures will trigger automatic retry attempts.

Ad content may take some time to load after creating an ad instance.
To ensure the ad displays instantly when needed, load the ad instance in advance.

### Conditions
- On Rewarded Ad Loaded: Triggered when an Rewarded ad is successfully loaded.
- On Rewarded Ad Failed to Load: Triggered when an Rewarded ad fails to load.
- Is Rewarded Ad Loaded: Checks if an Rewarded ad is loaded.


## Show Rewarded ad
When you show a rewarded ad, you will use an `On ad user earned reward` condition to handle reward for the user.

This action works asynchronously, and you can use the `Wait for previous actions to complete` action to wait until the ad has been dismissed or failed to show.

### Conditions
- **On Rewarded ad user earned reward**: Triggered when the user earns a reward from a rewarded ad.
- On Rewarded ad canceled by user: Triggered when the user cancel a rewarded ad and must not earn reward.

- On Rewarded Ad Failed to Show: Triggered when an Rewarded ad fails to show.
- On Rewarded Ad Showed: Triggered when an Rewarded ad is shown.
- On Rewarded Ad Clicked: Triggered when an Rewarded ad is clicked.
- On Rewarded Ad Dismissed: Triggered when an Rewarded ad is dismissed.

The `On ad user earned reward` condition differs from the `On Ad Dismissed` condition, the user might not complete the ad and thus not earn a reward, in this case triggered the `On ad canceled by user` condition.

There is no need to check whether the ad is loaded before showing it. If the ad is not ready at that moment, the `On ad failed to show` condition will be triggered.

<Info>
When an error occurs during ad impression, only the `On ad failed to show` condition is triggered.  
In this case, the `On ad dismissed` condition will not be fired since the impression is not considered successful.
</Info>

## Destroy Rewarded ad
Destroys the Rewarded ad instance and frees up resources. To resume working with ads, use the load ad action.
```

### User Consent Flow

Source: https://production.docs.page/docs/construct/user-consent-flow

```mdx

<Info>
It is optional to use the CMP flow included with the CAS SDK. If you integrate your own CMP flow, make sure that flow completes before you initialize the CAS SDK.
</Info>

<Info>
If you implement a CMP that is compliant with IAB TCF v2 ([Transparency & Consent Framework](https://iabeurope.eu/tcf-2-0/)) for your user consent flow, the CAS SDK supports sending the TCF v2 consent to networks. In this case, the CAS Consent Flow will not be shown to the user.
</Info>

In order for CAS and our ad providers to deliver ads that are more relevant to your users, as a mobile app publisher, you need to collect explicit user consent for use of personal data in the regions covered by GDPR, CCPA, LGPD, PIPEDA.

### 1. Opt-in consent for the collection and use of personal data in the regions covered by GDPR, CCPA, LGPD, PIPEDA.
Any businesses established are required to comply with GDPR in Europe, CCPA in California, LGPD in Brazil, PIPEDA in Canada or risk facing heavy fines.

Keep in mind that it’s best to contact qualified legal professionals, if you haven’t done so already, to get more information and be well-prepared for compliance.

Read more about:

* GDPR - [General Data Protection Regulation](https://gdpr-info.eu)
* CCPA - [The California Consumer Privacy Act](https://theccpa.org)
* LGPD - [General Personal Data Protection Act](https://lgpd-brazil.info)
* PIPEDA - [The Personal Information Protection and Electronic Documents Act](https://www.priv.gc.ca/en/privacy-topics/privacy-laws-in-canada/the-personal-information-protection-and-electronic-documents-act-pipeda/)

<Image height="400" alt="image" src="/assets/User-Consent-Flow-1.png" />

#### Users will not see the Consent dialog if at least one of following is true
* Users located in regions that are not covered by information protection
* Users who are subject to COPPA restrictions.

### 2. Asking user permission to track them or access their device’s advertising identifier
With iOS 14.5 and later, you need to receive the user’s permission through the `AppTrackingTransparency` framework in order to track them or access their device’s advertising identifier.  Read more about Asking Permission to Track and AppTrackingTransparency Framework on [Apple developer page](https://developer.apple.com/app-store/user-privacy-and-data-use/)

<Warning>  
If an app does not present this request, the IDFA will automatically be zeroed out, which may lead to a significant loss in ad revenue.
</Warning>

#### Users will not see the ATT request if at least one of the following is true
* Users using iOS versions below 14.5
* Users who have indicated that they do not allow apps to ask to track them, by setting *Settings > Privacy, Allow Apps to Request to Track*
* Users with child accounts, or who are under age 18, who are signed in via their Apple ID
* Users who have already answered so far
* The app does not have a usage tracking description in `IOS_USER_TRACKING_USAGE` variable.

## Automatic consent flow
The automatic consent flow is enabled by default and described on the [Automation options page](construct/automation-options).

## Conditions
- On Consent Form Dismissed: Triggered when the consent form is dismissed after CAS initialization or manual consent form show.
- On Consent Required: Triggered when user consent is required  after CAS initialization or manual consent form show.
- On Consent Not Required: Triggered when user consent is not required after CAS initialization or manual consent flow show.
- Is Consent Required: Checks if user consent is required.

## Manual consent flow
Perform `Show Consent Form` action to show the built-in consent form manually. If the consent is required, the SDK loads the form and immediately presents it.

<Property name="If required only" type="boolean">
Shows the consent form only if it is required and the user has not responded previously.
</Property>

## Consent Status
Gets the current status of the consent form.

| Consent Flow status  | Description                                                        |
| ---------------------- | ------------------------------------------------------------------ |
| `Obtained`               | User consent obtained. Personalized vs non-personalized undefined. |
| `Not required`           | User consent not required.                                         |
| `Unavailable`            | User consent unavailable.                                          |
| `Internal error`         | There was an internal error.                                       |
| `Network error`          | There was an error loading data from the network.                  |
| `Invalid context`        | There was an invalid context to display form.                      |
| `Still presenting`       | There was an error with another form is still being displayed.     |

<Warning>  
The cache consent status on your app or a previously saved consent string, could lead to a [TCF 3.3](https://support.google.com/admanager/answer/9999955) error if consent is expired.
</Warning>

## User Country Code
Gets the user's country ISO 2 code based on their IP address. For example: `'US'` or `'--'` if unknown.

## Privacy options button
Some consent forms require the user to modify their consent at any time. Adhere to the following steps to implement a privacy options button if required.

<Steps>
<Step>
Implement a UI element, such as a button in your app's settings page, that can trigger a privacy options form.
</Step>
<Step>
Check `Is Consent Required` condition to determine whether to display the UI element that can present the privacy options form.
</Step>
<Step>
When a user interacts with your UI element, call `Show Consent Form` action with false for `If required only` property to show the form so the user can update their privacy options at any time.
</Step>
</Steps>
```

### Ad errors

Source: https://production.docs.page/docs/cordova/ad-errors

```mdx

In cases where an ad fails to load/show, a `Promise` is rejected which provides a `AdError` object.

AdError is commonly used in ad-related events such as `'casai_ad_load_failed'` or `'casai_ad_show_failed'`.

## AdError

<Property name="code" type="number">
  Numeric error code returned by the SDK.
</Property>

---

<Property name="message" type="string">
  Human-readable error message.
</Property>

---

<Property name="format" type="AdFormat">
  The format of the ad that is shown. 
</Property>

## Ad error codes

| Code | Name        | Description                                                                                                                                                                                            |
| ---- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 0    | InternalError      | Indicates an internal error occurred.                                                                                                                                                                  |
| 1    | NotReady           | Indicates that ads are not ready to be shown. Ensure to call the appropriate ad loading method or use automatic load mode. If using automatic load mode, wait a little longer for ads to be ready.     |
| 2    | Rejected           | Indicates that the device is rejected for services. Services may not be available for some devices that do not meet the requirements. For example, the country or version of the OS.                   |
| 3    | NoFill             | Indicates that no ads are available to be served. If ads are visible in test ads mode, your implementation is correct, and ads will be served once live.                                               |
| 6    | ReachedCap         | Indicates that the ad creative has reached its daily cap for the user. This is typically relevant for cross-promotion ads only.                                                                        |
| 7    | NotInitialized     | Indicates that the CAS SDK is not initialized. Ensure to add CAS initialization code.                                                                                                                  |
| 8    | Timeout            | Indicates a timeout error occurred because the advertising source did not respond in time. The system will continue waiting for a response, which may delay ad loading or cause a loading error.       |
| 9    | NoConnection       | Indicates that there is no internet connection available, which prevents ads from loading.                                                                                                             |
| 10   | ConfigurationError | Indicates that there is a configuration error in one of the mediation ad sources. Report this error to your support manager for further assistance.                                                    |
| 11   | NotPassedInterval  | Indicates that the interval between impressions of interstitial ads has not yet passed. This error may also occur if a trial ad-free interval has been defined and has not yet passed since app start. |
| 12   | AlreadyDisplayed   | Indicates that another fullscreen ad is currently being displayed, preventing new ads from showing. Review your ad display logic to avoid duplicate impressions.                                       |
| 13   | NotForeground      | Indicates that ads cannot be shown because the application is not currently in the foreground.                                                                                                         |
```

### Additional Meta AudienceNetwork steps

Source: https://production.docs.page/docs/cordova/additional-meta-audiencenetwork-steps

```mdx

## Data Processing Options for US Users
Meta Audience Network Data Processing Options for US Users Limited Data Use is a data processing option that gives you more control over how your data is used in Meta’s systems and better supports your compliance efforts with various US state privacy regulations. To utilize this feature, you must proactively enable Limited Data Use.
Visit [Meta’s developer documentation](https://developers.facebook.com/docs/marketing-apis/data-processing-options) for details.

If you do not want to enable Limited Data Use (LDU) mode, pass an empty string as a value of mediation extras with key `FB_dp` in initialize method:
```js
casai.initialize({
  mediationExtras: { FB_dp: '' }, // [!code highlight]
});
```
To enable LDU for users and specify user geography, set `'LDU'` to `mediationExtras`:

```js
casai.initialize({
  mediationExtras: { FB_dp: 'LDU' }, // [!code highlight]
});
```
```

### App Open Ads

Source: https://production.docs.page/docs/cordova/app-open-ads

```mdx

App open ads are a special ad format intended for publishers wishing to monetize their app load screens.
App open ads can be closed at any time, and are designed to be shown when your users bring your app to the foreground.
App open ads automatically show a small branding area so users know they're in your app.

App open ad management in Cordova code is handled through the `casai.appOpenAd` object.
The app open ad is displayed as an overlay on top of all app content and cannot be added to the Cordova WebView DOM.

Below is a diagram showing the ad lifecycle and how autoload affects it.

<Image zoom src="/assets/Lifecycle-Screen-Ad.png" alt="Diagram" height="500" />

## Load Ad

CAS provides an option to enable autoload to simplify your app logic.  
Before using the ad, you should decide whether to enable autoload, or manually manage each ad loading cycle in your code.

When autoload is enabled, a new ad will be automatically loaded after each display, and loading failures will trigger automatic retry attempts.

<Tabs groupId="style">
  <TabItem value="promise" label="Promise">

```js
casai.appOpenAd
  .load({
    autoReload: true,
  })
  .then(function () {
    // Called when an ad is successfully loaded.
    console.log('Loaded');
  })
  .catch(function (error) {
    // Called when an ad load failed.
    console.log('Load failed:', error.message);
  });
```

  </TabItem>
  <TabItem value="async" label="Async">

```js
try {
  await casai.appOpenAd.load({
    autoReload: true,
  });
  // Called when an ad is successfully loaded.
  console.log('Loaded');
} catch (error) {
  // Called when an ad load failed.
  console.log('Load failed:', error.message);
}
```

  </TabItem>
  <TabItem value="events" label="Events">

```js
function onAdLoaded(event){
  if (event.format === casai.Format.APP_OPEN) {
    // Called when an ad is successfully loaded.
    console.log('Loaded');
  }
}

function onAdLoadFailed(event){
  if (event.format === casai.Format.APP_OPEN) {
    // Called when an ad load failed.
    console.log('Load failed:', event.message);
  }
}

document.addEventListener('casai_ad_loaded', onAdLoaded);
document.addEventListener('casai_ad_load_failed', onAdLoadFailed);

// Start loading, completion will be reported via document events
casai.appOpenAd.load({
  autoReload: true,
});

function unsubscribeAppOpenLoadEvents() {
  document.removeEventListener('casai_ad_loaded', onAdLoaded);
  document.removeEventListener('casai_ad_load_failed', onAdLoadFailed);
}
```

  </TabItem>
</Tabs>

Manual load mode is useful when you only need to show a single ad per app screen, and the screens change frequently.

When you want to manually control ad loading, use the `load({ autoReload: false })` function.
All parameters are optional — you can omit them and use the defaults if that fits your use case.

Ad content may take some time to load after creating an ad instance.
To ensure the ad displays instantly when needed, load the ad instance in advance.

You can use the `casai_ad_loaded` document event to be notified when the ad is ready for display.

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](cordova/impression-level-data).  
- Read more about [AdError](cordova/ad-errors) structure.
</Info>

## Show Ad

App open ads help you monetize your app's loading screen, when the app first launches and during app switches, but it's important to keep best practices in mind so that your users enjoy using your app. It's best to:

* Show your first app open ad after your users have used your app a few times.
* Show app open ads during times when your users would otherwise be waiting for your app to load.
* If a user returns to your app after having left it by clicking on an app open ad, make sure they're not presented with another app open ad immediately.

You can choose when to show the ad by calling `show()`:

<Tabs groupId="style">
  <TabItem value="promise" label="Promise">

```js
casai.appOpenAd
  .show()
  .then(function () {
    // Called when the ad dismissed full screen content.
    console.log('Dismissed');
  })
  .catch(function (error) {
    // Called when the ad failed to show full screen content.
    console.log('Failed to show:', error.message);
  });
```

  </TabItem>
  <TabItem value="async" label="Async">

```js
try {
  await casai.appOpenAd.show();
  // Called when the ad dismissed full screen content.
  console.log('Dismissed');
} catch (error) {
  // Called when the ad failed to show full screen content.
  console.log('Failed to show:', error.message);
}
```

  </TabItem>
  <TabItem value="events" label="Events">

```js
function onAdFailedToShow(event){
  if (event.format === casai.Format.APP_OPEN) {
    // Called when the ad failed to show full screen content.
    console.log('Failed to show:', event.message);
  }
}

function onAdShowed(event){
  if (event.format === casai.Format.APP_OPEN) {
    // Called when the ad showed the full screen content.
    console.log('Showed');
  }
}

function onAdDismissed(event){
  if (event.format === casai.Format.APP_OPEN) {
    // Called when the ad dismissed full screen content.
    console.log('Dismissed');
  }
}

document.addEventListener('casai_ad_show_failed', onAdFailedToShow);
document.addEventListener('casai_ad_showed', onAdShowed);
document.addEventListener('casai_ad_dismissed', onAdDismissed);

// Show without Promises - all results are handled via document events
casai.appOpenAd.show();

function unsubscribeAppOpenShowEvents() {
  document.removeEventListener('casai_ad_show_failed', onAdFailedToShow);
  document.removeEventListener('casai_ad_showed', onAdShowed);
  document.removeEventListener('casai_ad_dismissed', onAdDismissed);
}
```

<Info>
When an error occurs during ad impression, only the `casai_ad_show_failed` document event is triggered.  
In this case, the `casai_ad_dismissed` event will not be fired since the impression is not considered successful.
</Info>

  </TabItem>
</Tabs>

If the ad is not ready at that moment, the `casai_ad_show_failed` document event will be triggered with a reason provided in the `AdError`.

You have the option to check `isLoaded()` if it's required by your app's logic.

```js
if (await casai.appOpenAd.isLoaded()) {
  // The ad is loaded here
}
```

### Auto Show mode

CAS provides the option to automatically show a loaded ad when the user returns to the app.

To enable this behavior, set autoshow enabled:

```js
casai.appOpenAd.load({
  autoShow: true, // [!code highlight]
});
```

## Listening for the Ad Clicked
The plugin allows you to listen for the `casai_ad_clicked` event, which is triggered whenever a user clicks an ad. This can be useful for analytics, custom tracking, or UI reactions. You can check `e.format` to determine the ad format.
```js
function onAdClicked(event){
  if (event.format === casai.Format.APP_OPEN) {
    // Called when a click is recorded for an AppOpen ad.
  }
}

document.addEventListener('casai_ad_clicked', onAdClicked);
```

## Mute Ad sounds

Indicates if the application’s audio is muted. Affects initial mute state for fullscreen ads. Use this method only if your application has its own volume controls (e.g., custom music or sound effect muting).

```js
casai.setAdSoundsMuted(true);
```

Not muted by default.

## Release ad resource

Release ad resources when no longer needed.

```js
casai.appOpenAd.destroy();
```

## Cold starts and Loading screens

There is a delay between when you request an ad and when you receive an ad to show.
If you do not design your app well, the user may briefly see your app and then be surprised by an out-of-context ad.
Prevent this bad user experience. You can handle cold starts by showing a loading screen before any app content, and then showing the ad after the loading screen.
If your app shows any app content after the loading screen, do not show the ad.

## Best Practices

* When an app open ad is not yet loaded (i.e. on cold start), load it first. Load any other ad formats later so that you avoid loading them in parallel with the app open ad. Loading multiple ad formats in parallel is not good for the device’s resources or for ad demand SDKs.
* If you have a loading screen under the app open ad, and your loading screen completes loading before the ad is dismissed, you may want to dismiss your loading screen in the `casai_ad_dismissed` and `casai_ad_show_failed` document event listeners.
* Wait a variable number of days after initial install to show on cold start.
* Only show an ad if the user backgrounds the app for a certain amount of time (i.e. 30 seconds).
* If you show a cold start ad, do not show soft launch app open ads or interstitials for a certain amount of time.
* Include a call-out to the user that tells them they will see an ad in the Splash/Loading screen. For example: “Watch an ad from our sponsor while the app loads.”

## Complete example
- [AppOpen ad example](https://github.com/cleveradssolutions/CAS-Cordova/blob/main/example/src/AppOpenExample.tsx)
```

### Banner Ads

Source: https://production.docs.page/docs/cordova/banner-ads

```mdx

Banner Ad units display rectangular ads that occupy a portion of an app's layout.
They can refresh automatically after a set period of time.
This means users view a new ad at regular intervals, even if they stay on the same screen in your app.
They're also the simplest ad format to implement.

Banner ad management in Cordova code is handled through the `casai.bannerAd` object.

CAS provides an option to enable `autoReload` to simplify your app logic. The `autoReload` is enabled by default, loading failures will trigger automatic retry attempts.
You should decide whether to enable `autoReload`, or manually manage each ad loading cycle in your code.

Also, banner ads support automatic `refreshInterval` regardless of the `autoReload` setting.

Below is a diagram showing the ad lifecycle and how `autoReload` and `refreshInterval` affect it.
<Image zoom src="/assets/Lifecycle-Banner-Ad.png" alt="Diagram" height="500" />

## Get the Ad size
To load a banner ad, you need to specify the ad size. To do this, choose one of the `casai.Size` equivalents provided by the Cordova plugin:

1. **Adaptive banner** ads have a fixed aspect ratio for the maximum width. 
The adaptive size calculates the optimal height for that width with an aspect ratio similar to 320x50. 
By default, the full screen width will be used. You can limit width by specifying a `maxWidth` in the parameters.
```js
const adSize = casai.Size.ADAPTIVE;
```

2. **Inline banner** ads have a desired width and a maximum height, useful when you want to limit the banner's height. 
Inline banners are larger and taller compared to adaptive banners. They have variable height, including Medium Rectangle size, 
and can be as tall as the device screen. Specify the `maxWidth` and `maxHeight` dimensions to limit the ad size.
```js
const adSize = casai.Size.INLINE;
```

3. **Smart** selects the optimal dimensions depending on the device type. For mobile devices, it returns 320x50, while for tablets, it returns 728x90. In the UI, these banners occupy the same amount of space regardless of device type.
```js
const adSize = casai.Size.SMART;
```

4. **Leaderboard** has a fixed size of 728x90 and is allowed on tablets only.
```js
const adSize = casai.Size.LEADERBOARD;
```

5. **Standard Banner** has a fixed size of 320x50 and is the minimum ad size
```js
const adSize = casai.Size.BANNER;
```

## Load the Ad
The following example creates and loads an banner ad:

<Tabs groupId="style">
  <TabItem value="promise" label="Promise"> 
```js
casai.bannerAd.load({ 
  adSize: adSize, 
  autoReload: true,
  }) 
  .then(() => { 
    // Called when an ad is successfully loaded.
    console.log('Banner Ad loaded'); 
  }) 
  .catch((error) => { 
    // Called when an ad load failed.
    console.error('Banner Ad failed to load:', error.message); 
  }); 
``` 
  </TabItem> 
  <TabItem value="async" label="Async"> 
```js
try { 
  await casai.bannerAd.load({ 
    adSize: adSize, 
    autoReload: true,
  }); 
  // Called when an ad is successfully loaded.
  console.log('Banner Ad loaded'); 
} 
catch (error) {
  // Called when an ad load failed.
  console.error('Banner Ad failed to load:', error.message); 
} 
``` 
  </TabItem> 
  <TabItem value="events" label="Events"> 
```js
function onAdLoaded(event){
  if (event.format === casai.Format.BANNER) {
    // Called when an ad is successfully loaded.
    console.log('Banner Ad loaded');
  }
}

function onAdLoadFailed(event){
  if (event.format === casai.Format.BANNER) {
    // Called when an ad load failed.
    console.log('Banner Ad failed to load:', event.message);
  }
}

document.addEventListener('casai_ad_loaded', onAdLoaded);
document.addEventListener('casai_ad_load_failed', onAdLoadFailed);

casai.bannerAd.load({
  adSize: adSize,
  autoReload: true,
});

function unsubscribeInterstitialLoadEvents() {
  document.removeEventListener('casai_ad_loaded', onAdLoaded);
  document.removeEventListener('casai_ad_load_failed', onAdLoadFailed);
}
```
  </TabItem>
</Tabs>

Ad content may take some time to load after creating an ad instance. To ensure the ad displays instantly when needed, load the ad instance in advance. Use the `casai_ad_loaded` event or `Promise` to be notified when the ad is ready for display.

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](cordova/impression-level-data).  
- Read more about [AdError](cordova/ad-errors) structure.  
</Info>

## Limit the ad size
When using an AdSize based on screen width or height, you can restrict the ad size by specifying the `maxWidth` and `maxHeight` properties.

```js
casai.bannerAd.load({
  adSize: adSize,
  maxWidth: 400, // [!code highlight]
  maxHeight: 350, // [!code highlight]
})
```

<Property name="maxWidth" type="number">
Maximum width for `ADAPTIVE` and `INLINE` banners in Density-independent Pixels(DP).  
By default, adaptive and inline banners use the full device width.  
Automatically clamped to the screen bounds and updated on orientation changes.
</Property>

---

<Property name="maxHeight" type="number">
Maximum height for `INLINE` banners in Density-independent Pixels(DP).
By default, inline adaptive banners use the device height.
Automatically clamped to the screen bounds and updated on orientation changes.
</Property>


## Ad refresh interval
The automatic refresh interval determines how often a new ad request is generated. 
Once the interval elapses, a new ad will automatically load and display.

The interval countdown runs only while the ad is visible on screen. 

Set a custom refresh interval longer than 10 seconds, or 0 to disable refresh option. 
Default refresh interval is 30 seconds.

Override the automatic refresh interval in `refreshInterval` property:
```js
casai.bannerAd.load({ 
  adSize: adSize, 
  refreshInterval: 30, // [!code highlight]
}) 
```

## Display the Ad
The banner will not be visible until `show()` is called. The show function has a position parameter that specifies where the banner ad should be placed. The `casai.Position` lists the valid ad position values. By default, the banner ad is centered at the bottom. 
```js
casai.bannerAd.show({ 
  position: casai.Position.BOTTOM_CENTER,
});
```
To change the banner’s position on the screen, simply call the show function again with the new parameters.

The banner's activity can be changed even if it is not ready to be shown yet. When the ad becomes ready, it will be shown automatically if autoload/show logic requires it.

## The Ad coordinates on the screen
The offsetX and offsetY properties allow you to adjust the banner’s position relative to the specified anchor position, in DP. Our SDK will not allow an ad to be placed outside the screen or overlap with screen cutouts.

Some anchor positions do not support offset on the X or Y axis, this can be seen in the table as (X, Y).

|        | Left     | Center |    Right |
| ------ | -------- | :----: | -------: |
| Top    | TL(X, Y) | TC(Y)  | TR(X, Y) |
| Middle | ML(X)    | MC(-)  |    MR(X) |
| Bottom | BL(X, Y) | BC(Y)  | BR(X, Y) |

The coordinates on the screen are determined in Density-independent Pixels(DP).
```js
casai.bannerAd.show({ 
  position: casai.Position.TOP_LEFT,
  offsetX: xOffsetInDP,
  offsetY: yOffsetInDP
});
```

## Hide the Ad
When you need to hide the banner ad from the user, call:
```js
casai.bannerAd.hide();
```

## Listening for the Ad Clicked
The plugin allows you to listen for the `casai_ad_clicked` event, which is triggered whenever a user clicks an ad. This can be useful for analytics, custom tracking, or UI reactions. You can check `e.format` to determine the ad format.

```js
function onAdClicked(event){
  if (event.format === casai.Format.BANNER) {
    // Called when a click is recorded for an banner ad.
  }
}

document.addEventListener('casai_ad_clicked', onAdClicked);
```

## Release Ad resource
Destroys the ad content and releases any associated resources when the ad is no longer needed to clean up resources and prevent memory leaks.

```js
casai.bannerAd.destroy();
```

Call `load()` again to create and load a new ad instance and restore autoload behavior if needed.


## Complete example
- [Adaptive banner ad example](https://github.com/cleveradssolutions/CAS-Cordova/blob/main/example/www/js/AdaptiveBannerExample.js)
- [Standard banner ad example](https://github.com/cleveradssolutions/CAS-Cordova/blob/main/example/www/js/BannerExample.js)
```

### Enabling test ads

Source: https://production.docs.page/docs/cordova/enabling-test-ads

```mdx

It's important to enable test ads during development so that you can click on them without charging CAS advertisers.

<Error>  
We strongly suggest that you enable test ads mode when you validate the integration. If you click on too many ads without being in test mode, you risk your account being flagged for invalid activity.  
</Error>  

There are two ways to get test ads:
- [Enable test ad mode](cordova/enabling-test-ads#enable-test-ad-mode) for all devices.
- [Set device ids to test ad](cordova/enabling-test-ads#enable-test-devices).

Ads with Test Ads mode are safe to click. Requests, impressions, and clicks on test ads will not show up in your account's reports.
Test full-screen ads displays details of CAS integration and tips for solving errors. Go to the Mediation Adapters section to make sure that the advertising networks you want are integrated correctly.

<Image height="500" alt="image" src="/assets/Enabling-test-ads-1.jpg" />  
<Image height="500" alt="image" src="/assets/Enabling-test-ads-2.jpg" />  

## Enable Debug log mode
The enabled Debug Mode will display a lot of useful information for debugging about the states of the SDK with log tag `CAS`.
Disabled by default. Disabling Debug Mode may improve application performance.
```js
casai.setDebugLoggingEnabled(true);
```

<Info>  
If you have discovered the problem in the work of the SDK, please provide us with a description of the problem along with the full log of your device.  
</Info>  

## Enable test ad mode
The quickest way to enable testing is to use test ad mode. The test ad mode are not associated with your CAS account, so there's no risk of your account generating invalid traffic when using these test ad mode.
The easiest way to load test ads is to use:

```js
casai.initialize({
  forceTestAds: true, // [!code highlight]
});
```

## Enable test devices
If you want to do more rigorous testing with production-looking ads, you can now configure your device as a test device and use your own manager id. Test devices can either be added programmatically.

Follow the steps below to add your device as a test device.

1. Run an app configured with the CAS on device.
2. Check the logcat output for a message that looks like this:

```
To get test ads on this device, set "12345678901234567890123456789012"
```

3. Copy your alphanumeric test device ID to your clipboard.
4. Modify your code to set the test device ID through add `TestDeviceIDs` before CAS manager initialize.

```js
casai.initialize({
  testDeviceIds: ['12345678901234567890123456789012'],
});
```

<Info>  
Be sure to remove the code that sets these test devices before you release your app.  
</Info>  

5. Re-run your app.
6. Well done, ads on this device are safe to click. Requests, impressions, and clicks on ads in test mode will not show up in your account's reports.
```

### Impression Level Data

Source: https://production.docs.page/docs/cordova/impression-level-data

```mdx

CAS.AI SDK enables you to access detailed information for each impression through the impression callback APIs.  
The data includes which demand source served the ad and the exact or estimated revenue associated with it.  
This allows you to analyze and optimize your monetization and user acquisition strategies.

### AdContentInfo
The `AdContentInfo` structure contains information about a displayed ad.  

<Property name="format" type="string">
  The format of the ad that is shown. (e.g. `Banner`, `MREC`, `Interstitial`, `Rewarded`, `AppOpen`).
</Property>

---

<Property name="sourceName" type="string">
  The display name of the mediated network that purchased the impression.
</Property>

---

<Property name="sourceUnitId" type="string">
  The Ad Unit ID from the mediated network that purchased the impression.
</Property>

---

<Property name="creativeId" type="string" optional>
  The Creative ID associated with the ad, if available.
  You can use this ID to report creative issues to the Ad review team. 
</Property>

---

<Property name="revenue" type="number">
  The revenue generated from the impression, in USD. 
  The revenue value may be either estimated or exact, depending on the precision specified by `revenuePrecision`. 
</Property>

---

<Property name="revenuePrecision" type="string">
  The precision type of the revenue field. (e.g. `estimated`, `precise`, `floor`).
</Property>

---

<Property name="revenueTotal" type="number">
  The accumulated value of user ad revenue in USD from all ad format impressions. 
</Property>

---

<Property name="impressionDepth" type="number">
  The total number of impressions across all ad formats for the current user, across all sessions. 
</Property>


### Ad Impression event
Each ad impression triggers a `casai_ad_impressions` event with `AdContentInfo` details:

```js
document.removeEventListener('casai_ad_impressions', onAdImpression, false);
document.addEventListener('casai_ad_impressions', onAdImpression, false);

function onAdImpression(impression) {
  // Called when an ad impression occurs.  
  const adPlatform = 'CAS';
  const adFormat = impression.format;
  const adSource = impression.sourceName;
  const adUnitName = impression.sourceUnitId;
  const value = impression.revenue;
  // All CAS revenue is sent in USD  
  const currency = 'USD';
}
```

### User ad summary
CAS tracks cumulative impression and revenue metrics that are included in each `AdContentInfo` payload:

```js
const totalImpressions = impression.impressionDepth;
const totalRevenue = impression.revenueTotal;
```

<Info>
These counters persist between app sessions until the user clears your app’s data.
</Info>

## Automatic ad revenue collection
The CAS SDK have features to automatically collect ad revenue to Google Analytics and Tenjin Analytics. 
Contact your account manager for details of enabling automatic events.

### Google Analytics
To measure ad revenue with Google Analytics:
1. Get started with [Firebase Analytics](https://firebase.google.com/docs/analytics/get-started).
2. Link your Firebase project to a Google Analytics account.

The SDK automatically logs [`ad_impression`](https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#public-static-final-string-ad_impression)
events whenever an ad is displayed.
Events include parameters such as ad platform, source, currency, and value.
Alternatively, CAS may log the event as `CAS_Impression`.

### Tenjin
To measure ad revenue with Tenjin Analytics integrate the [Tenjin plugin](https://www.npmjs.com/package/cordova-plugin-tenjin) or just include Tenjin SDK by CAS PLugin variable:
```xml
<variable name="IOS_CAS_SOLUTIONS" value="... tenjin" />
<variable name="ANDROID_CAS_SOLUTIONS" value="... tenjin" />
```
CAS SDK automatically initializes the Tenjin SDK and sends ILRD if this option is enabled for your application.
```

### Initialize CAS SDK

Source: https://production.docs.page/docs/cordova/initialize-cas

```mdx

Before loading ads, initialize the CAS Mobile Ads SDK by calling `casai.initialize(options)` from the cordova `deviceready` event. The call returns a `Promise<InitializationStatus>` that resolves when initialization completes.

```js
function onDeviceReady() {
  document.removeEventListener('deviceready', onDeviceReady, false);

  casai.initialize({}).then((status) => {
    if (status.error) {
      console.log(`CAS initialization failed: ${status.error}`);
    } else {
      console.log(`CAS initialized`);
    }
  });
}

document.addEventListener("deviceready", onDeviceReady, false);
```

If an error occurs, the SDK attempts automatic re-initialization internally. However, the returned `Promise` is not updated with later status changes; call `initialize()` again for the latest `InitializationStatus`.

### Initialization Status

<Property name="error" type="string" optional>
Initialization error or null if success.
</Property>

---

<Property name="countryCode" type="string" optional>
User Country code ISO 2 or null if not allowed.
</Property>

---

<Property name="isConsentRequired" type="boolean">
Indicates the privacy options button is required.
</Property>

---

<Property name="consentFlowStatus" type="ConsentFlowStatus">
Consent flow status code, check `ConsentFlowStatus` enum values.
</Property>

## Automatic user consent flow
To collect user consent for personal data, use the built-in **Consent Flow**. It shows a consent form automatically during initialization.

```js
casai.initialize({
  showConsentFormIfRequired: true, // [!code highlight]
  debugGeography: 'eea'
}).then((status) => {
  if (status.consentFlowStatus == 'Obtained') {
    console.log('CAS obtained user consent');
  }
});
```

Wait for the consent flow to complete before initializing third-party SDKs (MMPs, analytics), otherwise they may not have access to required identifiers.

<Info>
Read more about **Debug geography** on [CAS User Consent Flow](cordova/user-consent-flow).
</Info>

## Always test with test ads
Enable test ads during development so you can interact with ads safely.

```js
casai.initialize({
  forceTestAds: true, // [!code highlight]
  testDeviceIds: ['YOUR_TEST_DEVICE_ID'], // [!code highlight]
});
```

For more on test ads, see [Enable test ads](cordova/enabling-test-ads).

## Prohibition on Personal Information from Children
Mark apps as child-directed or COPPA-applicable in the CAS UI. If you know specific users are COPPA-applicable, set the audience:

```js
casai.initialize({
  targetAudience: 'children', // [!code highlight]
});
```

- `'children'` - Compliance with all applicable legal regulations and industry standards relating to advertising to children.
- `'notchildren'` - Audiences over the age of 13 NOT subject to the restrictions of child protection laws.
- `undefined` - For app's target age groups include both children and older audiences, any ads that may be shown to children must comply with Google Play's Families Ads Program.

If your app targets both children and older users, implement a **neutral age screen** to ensure COPPA compliance.

## (Optional) Retrieve the Version Number
To programmatically retrieve the SDK version number at runtime, CAS provides the following method:
```js
const sdkVersion = await casai.getSDKVersion();
```

## (Optional) Trial ad-free interval
Defines the time interval, in seconds, starting from the moment of the initial app installation, during which users can use the application without ads being displayed while still retaining access to the Rewarded Ads format. Within this interval, users enjoy privileged access to the application's features without intrusive advertisements.  

```js
const secondsIn7Days = 604800;
casai.setTrialAdFreeInterval(secondsIn7Days);
```

## Complete example
- [Initialize casai example](https://github.com/cleveradssolutions/CAS-Cordova/blob/main/example/src/SetupScreen.tsx#L38)
```

### Interstitial Ads

Source: https://production.docs.page/docs/cordova/interstitial-ads

```mdx

Interstitial ads are full-screen ads that cover the interface of their host app.
They're typically displayed at natural transition points in the flow of an app, such as between screens.
When an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.

Interstitial ad management in Cordova code is handled through the `casai.interstitialAd` object.
The interstitial ad is displayed as an overlay on top of all app content and cannot be added to the Cordova WebView DOM.

Below is a diagram showing the ad lifecycle and how autoload affects it.

<Image zoom src="/assets/Lifecycle-Screen-Ad.png" alt="Diagram" height="500" />

## Load Ad

CAS provides an option to enable autoload to simplify your app logic.  
Before using the ad, you should decide whether to enable autoload, or manually manage each ad loading cycle in your code.

When autoload is enabled, a new ad will be automatically loaded after each display, and loading failures will trigger automatic retry attempts.

<Tabs groupId="style">
  <TabItem value="promise" label="Promise">

```js
casai.interstitialAd
  .load({
    autoReload: true,
  })
  .then(function () {
    // Called when an ad is successfully loaded.
    console.log('Loaded');
  })
  .catch(function (error) {
    // Called when an ad load failed.
    console.log('Load failed:', error.message);
  });
```

  </TabItem>
  <TabItem value="async" label="Async">

```js
try {
  await casai.interstitialAd.load({
    autoReload: true,
  });
  // Called when an ad is successfully loaded.
  console.log('Loaded');
} catch (error) {
  // Called when an ad load failed.
  console.log('Load failed:', error.message);
}
```

  </TabItem>
  <TabItem value="events" label="Events">

```js
function onAdLoaded(event){
  if (event.format === casai.Format.INTERSTITIAL) {
    // Called when an ad is successfully loaded.
    console.log('Loaded');
  }
}

function onAdLoadFailed(event){
  if (event.format === casai.Format.INTERSTITIAL) {
    // Called when an ad load failed.
    console.log('Load failed:', event.message);
  }
}

document.addEventListener('casai_ad_loaded', onAdLoaded);
document.addEventListener('casai_ad_load_failed', onAdLoadFailed);

// Start loading, completion will be reported via document events
casai.interstitialAd.load({
  autoReload: true,
});

function unsubscribeInterstitialLoadEvents() {
  document.removeEventListener('casai_ad_loaded', onAdLoaded);
  document.removeEventListener('casai_ad_load_failed', onAdLoadFailed);
}
```
  </TabItem>
</Tabs>

Manual load mode is useful when you only need to show a single ad per app screen, and the screens change frequently.

When you want to manually control ad loading, use the `load({ autoReload: false })` function.
All parameters are optional — you can omit them and use the defaults if that fits your use case.

Ad content may take some time to load after creating an ad instance.
To ensure the ad displays instantly when needed, load the ad instance in advance.

You can use the `casai_ad_loaded` document event to be notified when the ad is ready for display.

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](cordova/impression-level-data).  
- Read more about [AdError](cordova/ad-errors) structure. 
</Info>

## Show Ad

Interstitial ads should be displayed during natural pauses in the flow of an app. Between app screens is a good example, or after the user completes a task.

You can choose when to show the ad by calling:

<Tabs groupId="style">
  <TabItem value="promise" label="Promise">

```js
casai.interstitialAd
  .show()
  .then(function () {
    // Called when the ad dismissed full screen content.
    console.log('Dismissed');
  })
  .catch(function (error) {
    // Called when the ad failed to show full screen content.
    console.log('Failed to show:', error.message);
  });
```

  </TabItem>
  <TabItem value="async" label="Async">

```js
try {
  await casai.interstitialAd.show();
  // Called when the ad dismissed full screen content.
  console.log('Dismissed');
} catch (error) {
  // Called when the ad failed to show full screen content.
  console.log('Failed to show:', error.message);
}
```

  </TabItem>
  <TabItem value="events" label="Events">

```js
function onAdFailedToShow(event){
  if (event.format === casai.Format.INTERSTITIAL) {
    // Called when the ad failed to show full screen content.
    console.log('Failed to show:', event.message);
  }
}

function onAdShowed(event){
  if (event.format === casai.Format.INTERSTITIAL) {
    // Called when the ad showed the full screen content.
    console.log('Showed');
  }
}

function onAdDismissed(event){
  if (event.format === casai.Format.INTERSTITIAL) {
    // Called when the ad dismissed full screen content.
    console.log('Dismissed');
  }
}

document.addEventListener('casai_ad_show_failed', onAdFailedToShow);
document.addEventListener('casai_ad_showed', onAdShowed);
document.addEventListener('casai_ad_dismissed', onAdDismissed);

// Show without Promises - all results are handled via document events
casai.interstitialAd.show();

function unsubscribeInterstitialShowEvents() {
  document.removeEventListener('casai_ad_show_failed', onAdFailedToShow);
  document.removeEventListener('casai_ad_showed', onAdShowed);
  document.removeEventListener('casai_ad_dismissed', onAdDismissed);
}
```

<Info>
When an error occurs during ad impression, only the `casai_ad_show_failed` document event is triggered.  
In this case, the `casai_ad_dismissed` event will not be fired since the impression is not considered successful.
</Info>

  </TabItem>
</Tabs>

If the ad is not ready at that moment, the `casai_ad_show_failed` document event will be triggered with a reason.

You have the option to check `isLoaded()` if it's required by your app's logic.

```js
if (await casai.interstitialAd.isLoaded()) {
  // The ad is loaded here
}
```

### Auto Show Ad mode

CAS provides the option to automatically show a loaded ad when the user returns to the app.

To enable this behavior, set autoshow enabled:

```js
casai.interstitialAd.load({
  autoShow: true,
});
```

## Listening for the Ad Clicked
The plugin allows you to listen for the `casai_ad_clicked` event, which is triggered whenever a user clicks an ad. This can be useful for analytics, custom tracking, or UI reactions. You can check `e.format` to determine the ad format.
```js
function onAdClicked(event){
  if (event.format === casai.Format.INTERSTITIAL) {
    // Called when a click is recorded for an interstitial ad.
  }
}

document.addEventListener('casai_ad_clicked', onAdClicked);
```

## Minimum interval between impressions

The minimum interval between showing interstitial ads, in seconds.
Attempting to show a new interstitial ad before the interval has passed after the previous one was dismissed will trigger the `casai_ad_show_failed` document event with `AdErrorCode.NOT_PASSED_INTERVAL`.

```js
casai.interstitialAd.load({
  minInterval: 30, // seconds
});
```

Note that the timer for the minimum interval is shared across all interstitial ad instances, but the minimum interval value may differ for each ad instance.

## Mute Ad sounds

Indicates if the application’s audio is muted. Affects initial mute state for fullscreen ads. Use this method only if your application has its own volume controls (e.g., custom music or sound effect muting).

```js
casai.setAdSoundsMuted(true);
```

Not muted by default.

## Release ad resource

Be sure to release ad resources when no longer needed:

```js
casai.interstitialAd.destroy();
```

## Some best practices

#### Consider whether interstitial ads are the right type of ad for your app.

Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, like sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it's easy to present an interstitial ad without disrupting their experience. Make sure you consider at which points in your app's workflow you'll display interstitial ads and how the user is likely to respond.

#### Remember to pause the action when displaying an interstitial ad.

There are a number of different types of interstitial ads: text, image, video, and more. It's important to make sure that when your app displays an interstitial ad, it also suspends its use of some resources to allow the ad to take advantage of them. For example, when you make the call to display an interstitial ad, be sure to pause any audio output being produced by your app.

#### Allow for adequate loading time.

Just as it's important to make sure you display interstitial ads at an appropriate time, it's also important to make sure the user doesn't have to wait for them to load. Loading the ad in advance by calling `load()` before you intend to call `show()` can ensure that your app has a fully loaded interstitial ad at the ready when the time comes to display one.

#### Don't flood the user with ads.

While increasing the frequency of interstitial ads in your app might seem like a great way to increase revenue, it can also degrade the user experience and lower clickthrough rates. Make sure that users aren't so frequently interrupted that they're no longer able to enjoy the use of your app.

## Complete example
- [Interstitial ad example](https://github.com/cleveradssolutions/CAS-Cordova/blob/main/example/src/InterstitialExample.tsx)
```

### Medium Rectangle Banner Ads

Source: https://production.docs.page/docs/cordova/mrec-ads

```mdx

Medium Rectangle (MREC) are rectangular image or text ads that occupy a spot with size in dp (300x250) on screen. 
They stay on screen while users are interacting with the app, and can refresh automatically after a certain period of time. 

Medium Rectangle ad management in Cordova code is handled through the `casai.mrecAd` object.

CAS provides an option to enable `autoReload` to simplify your app logic. The `autoReload` is enabled by default, loading failures will trigger automatic retry attempts.
You should decide whether to enable `autoReload`, or manually manage each ad loading cycle in your code.

Also, banner ads support automatic `refreshInterval` regardless of the `autoReload` setting.

Below is a diagram showing the ad lifecycle and how `autoReload` and `refreshInterval` affect it.

<Image zoom src="/assets/Lifecycle-Banner-Ad.png" alt="Diagram" height="500" />

## Load the Ad
The following example creates and loads an Medium Rectangle (MREC) ad:

<Tabs groupId="style">
  <TabItem value="promise" label="Promise">
```js
casai.mrecAd.load({
  autoReload: true,
})
.then(() => {
  // Called when an ad is successfully loaded.
  console.log('MREC Ad loaded');
})
.catch((error) => {
  // Called when an ad load failed.
  console.error('MREC Ad failed to load:', error.message);
});
```
  </TabItem>
  <TabItem value="async" label="Async"> 
```js 
try { 
  await casai.mrecAd.load({ 
    autoReload: true,
  }); 
  // Called when an ad is successfully loaded.
  console.log('MREC Ad loaded'); 
} 
catch (error) { 
  // Called when an ad load failed.
  console.error('MREC Ad failed to load:', error.message); 
}
``` 
  </TabItem> 
  <TabItem value="events" label="Events"> 
```js
function onAdLoaded(event){
  if (event.format === casai.Format.MREC) {
    // Called when an ad is successfully loaded.
    console.log('MREC Ad loaded');
  }
}

function onAdLoadFailed(event){
  if (event.format === casai.Format.MREC) {
    // Called when an ad load failed.
    console.log('MREC Ad failed to load:', event.message);
  }
}

document.addEventListener('casai_ad_loaded', onAdLoaded);
document.addEventListener('casai_ad_load_failed', onAdLoadFailed);

casai.mrecAd.load({  
  autoReload: true,
});

function unsubscribeInterstitialLoadEvents() {
  document.removeEventListener('casai_ad_loaded', onAdLoaded);
  document.removeEventListener('casai_ad_load_failed', onAdLoadFailed);
}
```
  </TabItem>
</Tabs>

Ad content may take some time to load after creating an ad instance. To ensure the ad displays instantly when needed, load the ad instance in advance. Use the `casai_ad_loaded` event or `Promise` to be notified when the ad is ready for display.

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](cordova/impression-level-data).  
- Read more about [AdError](cordova/ad-errors) structure.  
</Info>

## Ad refresh interval
The automatic refresh interval determines how often a new ad request is generated. 
Once the interval elapses, a new ad will automatically load and display.

The interval countdown runs only while the ad is visible on screen. 

Set a custom refresh interval longer than 10 seconds, or 0 to disable refresh option. 
Default refresh interval is 30 seconds.

Override the automatic refresh interval in `refreshInterval` property:
```js
casai.mrecAd.load({ 
  adSize: adSize, 
  refreshInterval: 30, // [!code highlight]
}) 
```

## Display the Ad
The banner will not be visible until `show()` is called. The show function has a position parameter that specifies where the banner ad should be placed. The `casai.Position` lists the valid ad position values. By default, the banner ad is centered at the bottom. 
```js
casai.mrecAd.show({ 
  position: casai.Position.BOTTOM_CENTER,
});
```
To change the banner’s position on the screen, simply call the show function again with the new parameters.

The banner's activity can be changed even if it is not ready to be shown yet. When the ad becomes ready, it will be shown automatically if autoload/show logic requires it.

## The Ad coordinates on the screen
The offsetX and offsetY properties allow you to adjust the banner’s position relative to the specified anchor position, in DP. Our SDK will not allow an ad to be placed outside the screen or overlap with screen cutouts.

Some anchor positions do not support offset on the X or Y axis, this can be seen in the table as (X, Y).

|        | Left     | Center |    Right |
| ------ | -------- | :----: | -------: |
| Top    | TL(X, Y) | TC(Y)  | TR(X, Y) |
| Middle | ML(X)    | MC(-)  |    MR(X) |
| Bottom | BL(X, Y) | BC(Y)  | BR(X, Y) |

The coordinates on the screen are determined in Density-independent Pixels(DP).
```js
casai.mrecAd.show({ 
  position: casai.Position.TOP_LEFT,
  offsetX: xOffsetInDP,
  offsetY: yOffsetInDP
});
```

## Hide the Ad
When you need to hide the banner ad from the user, call:
```js
casai.mrecAd.hide();
```

## Listening for the Ad Clicked
The plugin allows you to listen for the `casai_ad_clicked` event, which is triggered whenever a user clicks an ad. This can be useful for analytics, custom tracking, or UI reactions. You can check `e.format` to determine the ad format.
```js
function onAdClicked(event){
  if (event.format === casai.Format.MREC) {
    // Called when a click is recorded for an MREC ad.
  }
}

document.addEventListener('casai_ad_clicked', onAdClicked);
```

## Release Ad resource
Destroys the ad content and releases any associated resources when the ad is no longer needed to prevent memory leaks.
```js
casai.mrecAd.destroy();
```

Call `load()` again to create and load a new ad instance and restore autoload behavior if needed.

## Complete example
- [Standard MREC ad example](https://github.com/cleveradssolutions/CAS-Cordova/blob/main/example/www/js/MRecExample.js)
```

### Rewarded Ads

Source: https://production.docs.page/docs/cordova/rewarded-ads

```mdx

Rewarded ads let you offer users in-app items, such as continued gameplay, virtual currency, or other rewards, in exchange for their engagement with ads.
Rewarded ads boost engagement because users receive a tangible benefit for their time.

Rewarded ad management in Cordova code is handled through the `casai.rewardedAd` object.
The rewarded ad is displayed as an overlay on top of all app content and cannot be added to the Cordova WebView DOM.

Below is a diagram showing the ad lifecycle and how autoload affects it.

<Image zoom src="/assets/Lifecycle-Rewarded-Ad.png" alt="Diagram" height="500" />

## Load Ad

CAS provides an option to enable autoload to simplify your app logic.  
Before using the ad, you should decide whether to enable autoload, or manually manage each ad loading cycle in your code.

When autoload is enabled, a new ad will be automatically loaded after each display, and loading failures will trigger automatic retry attempts.

<Tabs groupId="style">
  <TabItem value="promise" label="Promise">

```js
casai.rewardedAd
  .load({
    autoReload: true,
  })
  .then(function () {
    // Called when an ad is successfully loaded.
    console.log('Loaded');
  })
  .catch(function (error) {
    // Called when an ad load failed.
    console.log('Load failed:', error.message);
  });
```

  </TabItem>
  <TabItem value="async" label="Async">

```js
try {
  await casai.rewardedAd.load({
    autoReload: true,
  });
  // Called when an ad is successfully loaded.
  console.log('Loaded');
} catch (error) {
  // Called when an ad load failed.
  console.log('Load failed:', error.message);
}
```

  </TabItem>
  <TabItem value="events" label="Events">

```js
function onAdLoaded(event){
  if (event.format === casai.Format.REWARDED) {
    // Called when an ad is successfully loaded.
    console.log('Loaded');
  }
}

function onAdLoadFailed(event){
  if (event.format === casai.Format.REWARDED) {
    // Called when an ad load failed.
    console.log('Load failed:', event.message);
  }
}

document.addEventListener('casai_ad_loaded', onAdLoaded);
document.addEventListener('casai_ad_load_failed', onAdLoadFailed);

// Start loading, completion will be reported via document events
casai.rewardedAd.load({
  autoReload: true,
});

function unsubscribeRewardedLoadEvents() {
  document.removeEventListener('casai_ad_loaded', onAdLoaded);
  document.removeEventListener('casai_ad_load_failed', onAdLoadFailed);
}
```
  </TabItem>
</Tabs>

Manual load mode is useful when you only need to show a single ad per app screen, and the screens change frequently.

When you want to manually control ad loading, use the `load({ autoReload: false })` function.
All parameters are optional — you can omit them and use the defaults if that fits your use case.

Ad content may take some time to load after creating an ad instance.
To ensure the ad displays instantly when needed, load the ad instance in advance.

You can use the `casai_ad_loaded` document event to be notified when the ad is ready for display.

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](cordova/impression-level-data).  
- Read more about [AdError](cordova/ad-errors) structure.
</Info>

## Show Ad

Be sure to listen to the `casai_ad_reward` event or handle the resolved result from `show()` and reward the user for watching an ad.

You can choose when to show the ad by calling `show()`:

<Tabs groupId="style">
  <TabItem value="promise" label="Promise">

```js
casai.rewardedAd
  .show()
  .then(function (info) {
    if (info.isUserEarnReward) {
      // Called when the user has earned the reward.
      console.log('Reward the user for watching the ad');
    } else {
      // Called when the ad dismissed full screen content without a reward.
      console.log('Dismissed without reward');
    }
  })
  .catch(function (error) {
    // Called when the ad failed to show full screen content.
    console.log('Failed to show:', error.message);
  });
```

  </TabItem>
  <TabItem value="async" label="Async">

```js
try {
  const info = await casai.rewardedAd.show();

  if (info.isUserEarnReward) {
    // Called when the user has earned the reward.
    console.log('Reward the user for watching the ad');
  } else {
    // Called when the ad dismissed full screen content without a reward.
    console.log('Dismissed without reward');
  }
} catch (error) {
  // Called when the ad failed to show full screen content.
  console.log('Failed to show:', error.message);
}
```

  </TabItem>
  <TabItem value="events" label="Events">

```js
function onAdReward(event){
  if (event.format === casai.Format.REWARDED) {
    // Called when the user has earned the reward.
    console.log('Reward the user for watching the ad');
  }
}

function onAdFailedToShow(event){
  if (event.format === casai.Format.REWARDED) {
    // Called when the ad failed to show full screen content.
    console.log('Failed to show:', event.message);
  }
}

function onAdShowed(event){
  if (event.format === casai.Format.REWARDED) {
    // Called when the ad showed the full screen content.
    console.log('Showed');
  }
}

function onAdDismissed(event){
  if (event.format === casai.Format.REWARDED) {
    // Called when the ad dismissed full screen content.
    console.log('Dismissed');
  }
}

document.addEventListener('casai_ad_reward', onAdReward);
document.addEventListener('casai_ad_show_failed', onAdFailedToShow);
document.addEventListener('casai_ad_showed', onAdShowed);
document.addEventListener('casai_ad_dismissed', onAdDismissed);

// Show without Promises - all results are handled via document events
casai.rewardedAd.show();

function unsubscribeRewardedShowEvents() {
  document.removeEventListener('casai_ad_reward', onAdReward);
  document.removeEventListener('casai_ad_show_failed', onAdFailedToShow);
  document.removeEventListener('casai_ad_showed', onAdShowed);
  document.removeEventListener('casai_ad_dismissed', onAdDismissed);
}
```

<Info>
When an error occurs during ad impression, only the `casai_ad_show_failed` document event is triggered.  
In this case, the `casai_ad_dismissed` event will not be fired since the impression is not considered successful.
</Info>

  </TabItem>
</Tabs>

The reward event (`casai_ad_reward`) differs from the dismissal event (`casai_ad_dismissed`) — the user might not complete the ad and thus not earn a reward.

If the ad is not ready at that moment, the `casai_ad_show_failed` document event will be triggered with a reason provided in the `AdError`.

You have the option to check `isLoaded()` if it's required by your app's logic.

```js
if (await casai.rewardedAd.isLoaded()) {
  // The ad is loaded here
}
```

## Listening for the Ad Clicked
The plugin allows you to listen for the `casai_ad_clicked` event, which is triggered whenever a user clicks an ad. This can be useful for analytics, custom tracking, or UI reactions. You can check `e.format` to determine the ad format.
```js
function onAdClicked(event){
  if (event.format === casai.Format.REWARDED) {
    // Called when a click is recorded for an Rewarded ad.
  }
}

document.addEventListener('casai_ad_clicked', onAdClicked);
```

## Mute Ad sounds

Indicates if the application’s audio is muted. Affects initial mute state for fullscreen ads. Use this method only if your application has its own volume controls (e.g., custom music or sound effect muting).

```js
casai.setAdSoundsMuted(true);
```

Not muted by default.

## Release ad resource

Be sure to release ad resources when no longer needed:

```js
casai.rewardedAd.destroy();
```

## Complete example
- [Rewarded ad example](https://github.com/cleveradssolutions/CAS-Cordova/blob/main/example/src/RewardedExample.tsx)
```

### Targeting options

Source: https://production.docs.page/docs/cordova/targeting-options

```mdx

You can now easily tailor the way you serve your ads to fit a specific audience!
You’ll need to inform our servers of the users’ details so the SDK will know to serve ads according
to the segment the user belongs to.

### User Age
Set user age. Limitation: 1-99. By default 0 is 'unknown'.

```js
casai.setUserAge(12);
```

### User Gender

Set targeting to user’s gender. Limitation: `'male'`, `'female'`, `undefined`.

```js
casai.setUserGender('male');
``` 

### User Location auto collection
Collect from the device the latitude and longitude coordinated truncated to the hundredths decimal place.

* Collect only if your application already has the relevant end-user permissions.
- Does not collect if the target audience is children.
- Disabled by default.

```js
casai.setLocationCollectionEnabled(true);
```

### App Keywords
Set a list of keywords, interests, or intents related to your application. Words or phrases describe
the current activity of the user for targeting purposes.

```js
casai.setAppKeywords(keywords);
```

### App Content URL

Set the content URL for a website whose content matches the app's primary content. This website content is used for targeting and brand safety purposes. Limitation: max URL length 512.

```js
casai.setAppContentUrl(contentUrl);
```
```

### User Consent Flow

Source: https://production.docs.page/docs/cordova/user-consent-flow

```mdx

<Info>
It is optional to use the CMP flow included with the CAS SDK. If you integrate your own CMP flow, make sure that flow completes before you initialize the CAS SDK.
</Info>

<Info>
If you implement a CMP that is compliant with IAB TCF v2 ([Transparency & Consent Framework](https://iabeurope.eu/tcf-2-0/)) for your user consent flow, the CAS SDK supports sending the TCF v2 consent to networks. In this case, the CAS Consent Flow will not be shown to the user.
</Info>

In order for CAS and our ad providers to deliver ads that are more relevant to your users, as a mobile app publisher, you need to collect explicit user consent for use of personal data in the regions covered by GDPR, CCPA, LGPD, PIPEDA.

### 1. Opt-in consent for the collection and use of personal data in the regions covered by GDPR, CCPA, LGPD, PIPEDA.
Any businesses established are required to comply with GDPR in Europe, CCPA in California, LGPD in Brazil, PIPEDA in Canada or risk facing heavy fines.

Keep in mind that it’s best to contact qualified legal professionals, if you haven’t done so already, to get more information and be well-prepared for compliance.

Read more about:

* GDPR - [General Data Protection Regulation](https://gdpr-info.eu)
* CCPA - [The California Consumer Privacy Act](https://theccpa.org)
* LGPD - [General Personal Data Protection Act](https://lgpd-brazil.info)
* PIPEDA - [The Personal Information Protection and Electronic Documents Act](https://www.priv.gc.ca/en/privacy-topics/privacy-laws-in-canada/the-personal-information-protection-and-electronic-documents-act-pipeda/)

<Image height="400" alt="image" src="/assets/User-Consent-Flow-1.png" />

#### Users will not see the Consent dialog if at least one of following is true
* Users located in regions that are not covered by information protection
* Users who are subject to COPPA restrictions.

### 2. Asking user permission to track them or access their device’s advertising identifier
With iOS 14.5 and later, you need to receive the user’s permission through the `AppTrackingTransparency` framework in order to track them or access their device’s advertising identifier.  Read more about Asking Permission to Track and AppTrackingTransparency Framework on [Apple developer page](https://developer.apple.com/app-store/user-privacy-and-data-use/)

<Warning>  
If an app does not present this request, the IDFA will automatically be zeroed out, which may lead to a significant loss in ad revenue.
</Warning>

#### Users will not see the ATT request if at least one of the following is true
* Users using iOS versions below 14.5
* Users who have indicated that they do not allow apps to ask to track them, by setting *Settings > Privacy, Allow Apps to Request to Track*
* Users with child accounts, or who are under age 18, who are signed in via their Apple ID
* Users who have already answered so far
* The app does not have a usage tracking description in `IOS_USER_TRACKING_USAGE` variable.

## Automatic consent flow
The automatic consent flow is enabled by default and described on the [CAS initialization page](cordova/initialize-cas).

## Manual consent flow
Call `casai.showConsentFlow()` to show the built-in consent form manually. If the consent is required, the SDK loads the form and immediately presents it.  

The `Promise<ConsentFlowStatus>` completes after the form is dismissed. If consent is not required, the `Promise` resolves instantly.

```js
casai.showConsentFlow({
  ifRequired: true,
  debugGeography: 'eea'
}).then((status) => {
  if (status == 'Obtained') {
    // User consent obtained.
  }
});
```

| ConsentFlow constant   | Description                                                        |
| ---------------------- | ------------------------------------------------------------------ |
| `Obtained`               | User consent obtained. Personalized vs non-personalized undefined. |
| `Not required`           | User consent not required.                                         |
| `Unavailable`            | User consent unavailable.                                          |
| `Internal error`         | There was an internal error.                                       |
| `Network error`          | There was an error loading data from the network.                  |
| `Invalid context`        | There was an invalid context to display form.                      |
| `Still presenting`       | There was an error with another form is still being displayed.     |

<Warning>  
The cache consent status on your app or a previously saved consent string, could lead to a [TCF 3.3](https://support.google.com/admanager/answer/9999955) error if consent is expired.
</Warning>

## Privacy options button
Some consent forms require the user to modify their consent at any time. Adhere to the following steps to implement a privacy options button if required.

1. Implement a UI element, such as a button in your app's settings page, that can trigger a privacy options form.
2. Once `initialize()` completes, check `isConsentObtained` to determine whether to display the UI element that can present the privacy options form.
3. When a user interacts with your UI element, call `show()` to show the form so the user can update their privacy options at any time.

```js
var isConsentObtained = false;

function initialize() {
  casai.initialize({
    showConsentFormIfRequired: true,
  }).then((status) => {
    isConsentObtained = status.consentFlowStatus == `Obtained`; // [!code highlight]
  });
}

function showPrivacyOptionsForm() {
  casai.showConsentFlow({
    ifRequired: false
  }).then((status) => {
    isConsentObtained = status == `Obtained`;
  });
}
```

## Debug geography
The SDK provides a way to test your app's behavior as though the device was located in the EEA or UK using the `PrivacyGeography` enum.
Specify it in the SDK initialization arguments, and the setting will be applied only for test sessions.

```js
casai.initialize(casId, {
  forceTestAds: true,
  debugGeography: 'eea', // [!code highlight]
});
```

| PrivacyGeography         | Description                                   |
|---------------|----------------------------------------------------------|
| `unknown`     | Geography is unknown.                                    |
| `eea`         | Geography appears as in the European Economic Area.      |
| `us`          | Geography appears as in a regulated US State.            |
| `unregulated` | Geography appears as in a region with no regulation.     |

## Meta Audience Network Data Processing Options for Users in California
The CAS does not support your handling of CCPA opt-out values for Meta Audience Network, you must work directly with the network to purposes of your obligations for CCPA compliance.

To learn how to implement Meta Audience Network’s “Limited Data Use” flag, read the [Additional Meta AudienceNetwork steps](cordova/additional-meta-audiencenetwork-steps).
```

### Ad errors

Source: https://production.docs.page/docs/flutter/ad-errors

```mdx

In cases where an ad fails to load/show, a callback is called which provides a `AdError` object.

AdError is commonly used in ad-related callbacks such as `onAdFailedToLoad` or `onAdFailedToShow`.

Use `AdError.code` to retrieve the error code.   
Use `AdError.message` to get a human-readable error description.   

See `code` constants for all available error codes.

| Code | Constant               | Description                                                                                                                                                                                            |
| ---- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 0    | codeInternalError      | Indicates an internal error occurred.                                                                                                                                                                  |
| 1    | codeNotReady           | Indicates that ads are not ready to be shown. Ensure to call the appropriate ad loading method or use automatic load mode. If using automatic load mode, wait a little longer for ads to be ready.     |
| 2    | codeRejected           | Indicates that the device is rejected for services. Services may not be available for some devices that do not meet the requirements. For example, the country or version of the OS.                   |
| 3    | codeNoFill             | Indicates that no ads are available to be served. If ads are visible in test ads mode, your implementation is correct, and ads will be served once live.                                               |
| 6    | codeReachedCap         | Indicates that the ad creative has reached its daily cap for the user. This is typically relevant for cross-promotion ads only.                                                                        |
| 7    | codeNotInitialized     | Indicates that the CAS SDK is not initialized. Ensure to add CAS initialization code.                                                                                                                  |
| 8    | codeTimeout            | Indicates a timeout error occurred because the advertising source did not respond in time. The system will continue waiting for a response, which may delay ad loading or cause a loading error.       |
| 9    | codeNoConnection       | Indicates that there is no internet connection available, which prevents ads from loading.                                                                                                             |
| 10   | codeConfigurationError | Indicates that there is a configuration error in one of the mediation ad sources. Report this error to your support manager for further assistance.                                                    |
| 11   | codeNotPassedInterval  | Indicates that the interval between impressions of interstitial ads has not yet passed. This error may also occur if a trial ad-free interval has been defined and has not yet passed since app start. |
| 12   | codeAlreadyDisplayed   | Indicates that another fullscreen ad is currently being displayed, preventing new ads from showing. Review your ad display logic to avoid duplicate impressions.                                       |
| 13   | codeNotForeground      | Indicates that ads cannot be shown because the application is not currently in the foreground.                                                                                                         |
```

### Additional Meta AudienceNetwork steps

Source: https://production.docs.page/docs/flutter/additional-meta-audiencenetwork-steps

```mdx

## Data Processing Options for US Users
Meta Audience Network Data Processing Options for US Users Limited Data Use is a data processing option that gives you more control over how your data is used in Meta’s systems and better supports your compliance efforts with various US state privacy regulations. To utilize this feature, you must proactively enable Limited Data Use.
Visit [Meta’s developer documentation](https://developers.facebook.com/docs/marketing-apis/data-processing-options) for details.

If you do not want to enable Limited Data Use (LDU) mode, pass an empty string as a value of mediation extras with key `FB_dp` in initialize method:
```dart
CASMobileAds.initialize(
    casId: casId,
    mediationExtras: {'FB_dp': ''}, // [!code highlight]
    ...
);
```
To enable LDU for users and specify user geography, set `'LDU'` to `mediationExtras`:
```dart
CASMobileAds.initialize(
    casId: casId,
    mediationExtras: {'FB_dp': 'LDU'}, // [!code highlight]
    ...
);
```
```

### App Open Ads

Source: https://production.docs.page/docs/flutter/app-open-ads

```mdx

App open ads are a special ad format intended for publishers wishing to monetize their app load screens. 
App open ads can be closed at any time, and are designed to be shown when your users bring your app to the foreground. 
App open ads automatically show a small branding area so users know they're in your app.

AppOpen Ad management in Dart code is handled through the [CASAppOpen](https://pub.dev/documentation/clever_ads_solutions/latest/clever_ads_solutions/CASAppOpen-class.html) class, 
which extends the shared `AdScreenInstance` class used for all fullscreen ads. 
The `AdScreenInstance` class, inherits from the base `AdInstance` class, which is common for all CAS ad formats. 
The `AdScreenInstance` is displayed as an `Overlay` on top of all app content and is positioned statically; 
therefore, it cannot be added to the Flutter widget tree.

CAS provides an option to enable `autoReload` to simplify your app logic. Before using the ad, you should decide whether to enable `autoReload`, or manually manage each ad loading cycle in your code. 

When `autoReload` is enabled, a new ad will be automatically loaded after each display, and loading failures will trigger automatic retry attempts. 
```dart
final bool isAutoReloadEnabled = true;
```

Manual load mode (`autoReload: false` ) is useful when you only need to show a single ad per app screen, and the screens change frequently.  

Below is a diagram showing the ad lifecycle and how `autoReload` (isAutoload) affects it.

<Image zoom src="/assets/Lifecycle-Screen-Ad.png" alt="Diagram" height="500" />


## Create Ad instance
The following example creates and loads an app open ad:
```dart
class AppScreenState extends State<AppScreen> {
  late CASAppOpen _appOpenAd;
  
  @override
  void initState() {
    super.initState();
    
    _appOpenAd = CASAppOpen.createAndLoad( 
      autoReload: isAutoReloadEnabled, 
      onAdLoaded: (AdScreenInstance ad) { 
        // Called when an ad is successfully loaded. 
        print('$ad loaded');  
      },  
      onAdFailedToLoad: (AdInstance ad, AdError error) { 
        // Called when an ad load failed. 
        print('$ad failed to load: ${error.message}.'); 
      }, 
    ); 
  }
}
```

Ad content may take some time to load after creating an ad instance. To ensure the ad displays instantly when needed, create the ad instance in advance. Use the `onAdLoaded` callback to be notified when the ad is ready for display.

CAS provides functionality to create and preload multiple ad instances in advance, ensuring uninterrupted sequential ad delivery. Mediation ads are loaded in order for each created instance.

## Ad content callbacks
`CASAppOpen` has several optional callbacks for the ad lifecycle. These callbacks can be set either as arguments in the `createAndLoad()` function or later via the properties of the ad instance.

```dart
_appOpenAd.onAdFailedToShow = (AdInstance ad, AdError error) { 
  // Called when the ad failed to show full screen content. 
  print('$ad failed to show: ${error.message}.');  
  // TODO: dismissAppLoadingScreen();
};  
_appOpenAd.onAdShowed = (AdScreenInstance ad) {  
  // Called when the ad showed the full screen content.
  print('$ad showed');  
  // TODO: showAppLoadingScreen();
};  
_appOpenAd.onAdImpression = (AdInstance ad, AdContentInfo contentInfo) { 
  // Called when an impression occurs on the ad. 
  print('$ad impression');  
};  
_appOpenAd.onAdClicked = (AdInstance ad) {  
  // Called when a click is recorded for an ad.
  print('$ad clicked');  
};  
_appOpenAd.onAdDismissed = (AdScreenInstance ad) { 
  // Called when the ad dismissed full screen content. 
  print('$ad dismissed');  
  // TODO: dismissAppLoadingScreen();
};
```

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](flutter/impression-level-data).
- When an error occurs during ad impression, executed the `onAdFailedToShow` only.  In this case the `onAdDismissed` will not be executed, since the impression is not considered successful.
</Info>

## Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.

```dart
_appOpenAd = CASAppOpen.createAndLoad( 
  placement: "BestPlace", // [!code highlight]
)
```

## Show Ad
App open ads help you monetize your app's loading screen, when the app first launches and during app switches, but it's important to keep best practices in mind so that your users enjoy using your app. It's best to:
- Show your first app open ad after your users have used your app a few times.
- Show app open ads during times when your users would otherwise be waiting for your app to load.
- If a user returns to your app after having left it by clicking on an app open ad, it makes sure they're not presented with another app open ad.

You can choose when to show the ad by calling `show()`:
```dart
_appOpenAd.show()
```

If the ad is not ready at that moment, the `onAdFailedToShow` callback will be triggered with a reason provided in the `AdError`.

You have the option to check `isLoaded` if it's required by your app's logic.
```dart
bool isAdLoaded = await _appOpenAd.isLoaded();
```

### Auto Show mode
CAS provides the option to automatically show a loaded ad when the user returns to the app. To enable this behavior, set the `autoShow` argument to `true`.
```dart
_appOpenAd = CASAppOpen.createAndLoad(
  autoShow: true, // [!code highlight]
  ...
)
```

## Release ad resource
Be sure to release ad resources if you’re no longer going to use the ad instance.
```dart
  @override
  void dispose() {
    _appOpenAd.dispose(); // [!code highlight]
    super.dispose();
  }
```
It may be useful to store the ad instance in static memory for reuse across multiple screens. This way, you don't need to call `dispose()` and can show the already loaded ad without delay.

## Manual reload Ad
When you want to manually control ad loading, use the `load()` function on the created ad instance to retry loading with the same configuration.
```dart
_appOpenAd.load();
```

## Mute Ad sounds
Indicates if the application’s audio is muted. Affects initial mute state for fullscreen ads. Use this method only if your application has its own volume controls (e.g., custom music or sound effect muting).
```dart
CASMobileAds.setAdSoundsMuted(true);
```
Not muted by default.

## Cold starts and Loading screens
There is a delay between when you request an ad and when you receive an ad to show. 
If you do not design your app well, the user may briefly see your app and then be surprised by an out-of-context ad. 
Prevent this bad user experience. You can handle cold starts by showing a loading screen before any app content, and then showing the ad after the loading screen. 
If your app shows any app content after the loading screen, do not show the ad.

## Best Practices
- When an app open ad is not yet loaded (i.e. on cold start), load it first. Load any other ad formats later so that you avoid loading them in parallel with the app open ad. Loading multiple ad formats in parallel is not good for the device’s resources or for ad demand SDKs.
- If you have a loading screen under the app open ad, and your loading screen completes loading before the ad is dismissed, you may want to dismiss your loading screen in the `onAdDismissed` and `onAdFailedToShow` callbacks.
- Wait a variable number of days after initial install to show on cold start.
- Only show an ad if the user backgrounds the app for a certain amount of time (i.e. 30 seconds).
- If you show a cold start ad, do not show soft launch app open ads or interstitials for a certain amount of time.
- Include a call-out to the user that tells them they will see an ad in the Splash/Loading screen. For example: “Watch an ad from their sponsor while the app loads.”

## Complete example
- [AppOpen ad example](https://github.com/cleveradssolutions/CAS-Flutter/blob/main/example/lib/main.dart#L74)
```

### Banner Ads

Source: https://production.docs.page/docs/flutter/banner-ads

```mdx

Banner Ad units display rectangular ads that occupy a portion of an app's layout. 
They can refresh automatically after a set period of time. 
This means users view a new ad at regular intervals, even if they stay on the same screen in your app. 
They're also the simplest ad format to implement.

Banner Ad management in Dart code is handled through the [CASBanner](https://pub.dev/documentation/clever_ads_solutions/latest/clever_ads_solutions/CASBanner-class.html) class, 
which extends the shared `AdViewInstance` class used for all ads displayed in a widgets. 
The `AdViewInstance` class, inherits from the base `AdInstance` class, which is common for all CAS ad formats. 
To display a `AdViewInstance` as a widget, you must instantiate an `CASWidget` for each ad instance. 

CAS provides an option to enable `autoReload` to simplify your app logic. 
Before using the ad, you should decide whether to enable `autoReload`, or manually manage each ad loading cycle in your code. 

When `autoReload` is enabled, loading failures will trigger automatic retry attempts. 
```dart
final bool isAutoReloadEnabled = true;
```

Also, banner ads support automatic `refreshInterval` regardless of the `autoReload` setting.

Below is a diagram showing the ad lifecycle and how `autoReload` (isAutoload) and `refreshInterval` affects it.

<Image zoom src="/assets/Lifecycle-Banner-Ad.png" alt="Diagram" height="500" />


## Get the Ad size
To load a banner ad, you need to specify the ad size. To do this, choose one of the methods for obtaining an `AdSize` from the list below:
1. **Adaptive banner** ads have a fixed aspect ratio for the maximum width. The adaptive size calculates the optimal height for that width with an aspect ratio similar to 320x50.
```dart
final double maxWidth = MediaQuery.of(context).size.width;
final AdSize adSize = AdSize.getAdaptiveBanner(maxWidth);
```
2. **Inline banner** ads have a desired width and a maximum height, useful when you want to limit the banner's height. Inline banners are larger and taller compared to adaptive banners. They have variable height, including Medium Rectangle size, and can be as tall as the device screen.
```dart
final int width = MediaQuery.of(context).size.width.truncate();
final int maxHeight = 400;
final adSize = AdSize.getInlineBanner(width, maxHeight);
```
3. **Smart ad size** selects the optimal dimensions depending on the device type. For mobile devices, it returns 320x50, while for tablets, it returns 728x90. In the UI, these banners occupy the same amount of space regardless of device type.
```dart
final adSize = AdSize.getSmartBanner(context);
```
4. **Medium Rectangle** has a fixed size of 300x250.
```dart
final adSize = AdSize.mediumRectangle;
```
5. **Leaderboard** has a fixed size of 728x90 and is allowed on tablets only.
```dart
final adSize = AdSize.leaderboard;
```
6. **Standard banner** has a fixed size of 320x50 and is the minimum ad size.
```dart
final adSize = AdSize.banner;
```

## Create Ad instance
The following example creates and loads an banner ad:
```dart
class BannerAdExampleState extends State<BannerAdExample> {
  CASBanner? _bannerAd;
  
  void _loadAd(AdSize adSize) {
    // Disposing of the current ad if there is one.
    _bannerAd?.dispose();
  
    _bannerAd = CASBanner.createAndLoad( 
      size: adSize,
      autoReload: isAutoReloadEnabled, 
      onAdLoaded: (AdViewInstance ad) { 
        // Called when an ad is successfully loaded. 
        print('$ad loaded');  
      },  
      onAdFailedToLoad: (AdInstance ad, AdError error) { 
        // Called when an ad load failed. 
        print('$ad failed to load: ${error.message}.'); 
      }, 
    ); 
  }
}
```

Ad content may take some time to load after creating an ad instance. 
To ensure the ad displays instantly when needed, create the ad instance in advance. 
Use the `onAdLoaded` callback to be notified when the ad is ready for display.

When using an `AdSize` based on screen width, you should recalculate the size whenever 
the device orientation changes and reload the banner ad to match the new layout.
```dart
late Orientation _currentOrientation;

@override  
void didChangeDependencies() {  
  super.didChangeDependencies();
  MediaQueryData mediaQuery = MediaQuery.of(context);
  _currentOrientation = mediaQuery.orientation;
  
  final double maxWidth = mediaQuery.size.width;
  final AdSize adSize = ...;
  _loadAd(adSize);
}
```

When using a fixed ad size, it's enough to load the ad instance once in `initState()`.
```dart
@override  
void initState() {  
  super.initState();  
  
  final AdSize adSize = ...;
  _loadAd(adSize)  
}
```

## Ad refresh interval
The automatic refresh interval determines how often a new ad request is generated. 
Once the interval elapses, a new ad will automatically load and display.

The interval countdown runs only while the ad is visible on screen. 

Set a custom refresh interval longer than 10 seconds, or 0 to disable refresh option. 
Default refresh interval is 30 seconds.

Override the automatic refresh interval in `createAndLoad()` arguments:
```dart
    _bannerAd = CASBanner.createAndLoad( 
      size: adSize,
      autoReload: isAutoReloadEnabled, 
      refreshInterval: 30, // [!code highlight]
    );
```

## Ad content callbacks
`CASBanner` has several optional callbacks for the ad lifecycle. These callbacks can be set either as arguments in the `createAndLoad()` function or later via the properties of the ad instance.

```dart
    _bannerAd = CASBanner.createAndLoad( 
      size: adSize,
      autoReload: isAutoReloadEnabled, 
      onAdLoaded: (AdViewInstance ad) { 
        // Called when an ad is successfully loaded. 
        print('$ad loaded');  
      },  
      onAdFailedToLoad: (AdInstance ad, AdError error) { 
        // Called when an ad load failed. 
        print('$ad failed to load: ${error.message}.'); 
      }, 
      onAdImpression: (AdInstance ad, AdContentInfo contentInfo) { 
        // Called when an impression occurs on the ad.  
        print('$ad impression');  
      },  
      onAdClicked: (AdInstance ad) {  
        // Called when a click is recorded for an ad.
        print('$ad clicked');  
      },
    ); 
```

<Info>
Read more about `AdContentInfo` structure in [Impression Level Data](flutter/impression-level-data).
</Info>

## Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.

```dart
_bannerAd = CASBanner.createAndLoad( 
  size: adSize,
  placement: "BestPlace", // [!code highlight]
);
```

## Show Ad Widget
`CASWidget` inherits from Flutter's Widget class and can be used like any other widget.
```dart
@override  
Widget build(BuildContext context) {  
  return CASWidget(ad: _bannerAd!);  
}
```
While the ad is loading, the widget will have a size of (1x1). When the ad loads, the widget will automatically adopt the selected size.

The size of the container in which you place your ad must be at least as large as the AdSize. Any padding effectively decreases the size of your container.

## Release ad resource
Be sure to release ad resources if you’re no longer going to use the ad instance.
```dart
  @override
  void dispose() {
    _bannerAd?.dispose(); // [!code highlight]
    super.dispose();
  }
```

## Manual reload Ad
When you want to manually control ad loading, use the `load()` function on the created ad instance to retry loading with the same configuration.
```dart
_bannerAd!.load();
```

## Complete example
- [Adaptive banner ad example](https://github.com/cleveradssolutions/CAS-Flutter/blob/main/example/lib/adaptive_banner_example.dart)
- [Inline banner ad example](https://github.com/cleveradssolutions/CAS-Flutter/blob/main/example/lib/inline_banner_example.dart)
- [Multi banners ad example](https://github.com/cleveradssolutions/CAS-Flutter/blob/main/example/lib/multi_banners_example.dart)
```

### Enabling test ads

Source: https://production.docs.page/docs/flutter/enabling-test-ads

```mdx

It's important to enable test ads during development so that you can click on them without charging CAS advertisers.

<Error>  
We strongly suggest that you enable test ads mode when you validate the integration. If you click on too many ads without being in test mode, you risk your account being flagged for invalid activity.
</Error>

There are two ways to get test ads:
- [Enable test ad mode](flutter/enabling-test-ads#enable-test-ad-mode) for all devices.
- [Set device ids to test ad](flutter/enabling-test-ads#enable-test-devices).

Ads with Test Ads mode are safe to click. Requests, impressions, and clicks on test ads will not show up in your account's reports.  
Test full-screen ads displays details of CAS integration and tips for solving errors. Go to the Mediation Adapters section to make sure that the advertising networks you want are integrated correctly.

<Image height="500" alt="image" src="/assets/Enabling-test-ads-1.jpg" />
<Image height="500" alt="image" src="/assets/Enabling-test-ads-2.jpg" />

## Enable Debug log mode
The enabled Debug Mode will display a lot of useful information for debugging about the states of the SDK with log tag `CAS`.    
Disabled by default. Disabling Debug Mode may improve application performance.
```dart
CASMobileAds.setDebugLoggingEnabled(true);
```

<Info>
If you have discovered the problem in the work of the SDK, please provide us with a description of the problem along with the full log of your device.
</Info>

## Enable test ad mode
The quickest way to enable testing is to use test ad mode. The test ad mode are not associated with your CAS account, so there's no risk of your account generating invalid traffic when using these test ad mode.

The easiest way to load test ads is to use:
```dart
CASMobileAds.initialize(
    casId: _casId,
    forceTestAds: kDebugMode || kProfileMode,,
);
```

## Enable test devices
If you want to do more rigorous testing with production-looking ads, you can now configure your device as a test device and use your own manager id. Test devices can either be added programmatically.

Follow the steps below to add your device as a test device.
1. Run an app configured with the CAS on device.
2. Check the logcat output for a message that looks like this:
```
To get test ads on this device, set "12345678901234567890123456789012"
```
3. Copy your alphanumeric test device ID to your clipboard.
4. Modify your code to set the test device ID through add `TestDeviceIDs` before CAS manager initialize.
```dart
CASMobileAds.initialize(
    casId: _casId,
    testDeviceIds: ['12345678901234567890123456789012'],
);
```
<Info>
Be sure to remove the code that sets these test devices before you release your app.
</Info>

5. Re-run your app.
6. Well done, ads on this device are safe to click. Requests, impressions, and clicks on ads in test mode will not show up in your account's reports.
```

### Impression Level Data

Source: https://production.docs.page/docs/flutter/impression-level-data

```mdx

CAS.AI SDK enables you to access detailed information for each impression through the impressions callback APIs. The information includes, for example, which demand source served the ad, the expected or exact revenue associated with it. In addition, it contains granular details to allow you to analyze and, ultimately, optimize user acquisition strategies.

### AdContentInfo
The `AdContentInfo` data structure, which contains information about a displayed ad. 

Additionally to `onAdImpression` callback, each ad format has a `getContentInfo()` method that returns `AdContentInfo?`, but the content info may be `null` before the ad is loaded.
```dart
AdContentInfo? info = await eachAd.getContentInfo();
```

<Property name="format" type="AdFormat">
  The format of the ad that is shown.
</Property>

---

<Property name="sourceName" type="String">
  The display name of the mediated network that purchased the impression.
</Property>

---

<Property name="sourceUnitId" type="String">
  The Ad Unit ID from the mediated network that purchased the impression.
</Property>

---

<Property name="creativeId" type="String?" optional>
  The Creative ID associated with the ad, if available.
  You can use this ID to report creative issues to the Ad review team. 
</Property>

---

<Property name="revenue" type="Double">
  The revenue generated from the impression, in USD. 
  The revenue value may be either estimated or exact, depending on the precision specified by `revenuePrecision`. 
</Property>

---

<Property name="revenuePrecision" type="Int">
  The precision type of the revenue field. See new `AdRevenuePrecision` constants.
</Property>

---

<Property name="revenueTotal" type="Double">
  The accumulated value of user ad revenue in USD from all ad format impressions. 
</Property>

---

<Property name="impressionDepth" type="Int">
  The total number of impressions across all ad formats for the current user, across all sessions. 
</Property>

### Ad Impression callback
A `onAdImpression` callback for ad impression with impression details in `AdContentInfo` for each ad formats:
```dart
CASAppOpen appOpenAd;
CASInterstitial interstitialAd;
CASRewarded rewardedAd;
CASBanner bannerAd;
NativeAdContent nativeAd;

void setAdImpressionCallback() {
  appOpenAd.onAdImpression = _onAdImpression;
  interstitialAd.onAdImpression = _onAdImpression;
  rewardedAd.onAdImpression = _onAdImpression;
  bannerAd.onAdImpression = _onAdImpression;
  nativeAd.onAdImpression = _onAdImpression;
}

void _onAdImpression(AdInstance ad, AdContentInfo contentInfo) {  
  // Called when an ad impression occurs.  
  String adPlatform = "CAS";  
  String adFormat = ad.format.label;  
  String adSource = contentInfo.sourceName;  
  String adUnitName = contentInfo.sourceUnitId;  
  double value = contentInfo.revenue;  
  // All CAS revenue is sent in USD  
  String currency = "USD";  
}
```

### User ad summary
CAS count the number of ad impressions and the total revenue of all formats at the time of a new impression.
```dart
int totalImpressions = impression.impressionDepth;
double totalRevenue = impression.revenueTotal;
```
<Info>
Progress is saved between sessions until the user clears your app's data.
</Info>

## Automatic collect ad revenue
The CAS SDK have features to automatically collect ad revenue to Google Analytics and Tenjin Analytics. Contact your account manager for details of enabling automatic events.

### Google Analytics
To measure ad revenue with Google Analytics:

1. Get started with [Firebase Analytics](https://firebase.google.com/docs/analytics/get-started).
2. Link your Firebase project to a Google Analytics account.

The SDK automatically logs [`ad_impression`](https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#public-static-final-string-ad_impression)
events whenever an ad is displayed.
Events include parameters such as ad platform, source, currency, and value.
Alternatively, CAS may log the event as `CAS_Impression`.

### Tenjin
To measure ad revenue with Tenjin Analytics integrate the [Tenjin SDK](https://pub.dev/packages/tenjin_plugin) or just include Tenjin SDK by CAS Gadle plugin and CAS Cocoapods:

<Tabs groupId="platform">
<TabItem label="Android" value="android">
```kotlin
cas {
    includeTenjinSDK = true
}
```
</TabItem>

<TabItem label="iOS" value="ios">
```ruby
pod 'CleverAdsSolutions-SDK/Tenjin', '{{ versions.ios }}'
```
</TabItem>
</Tabs>

CAS SDK automatically initializes the Tenjin SDK and sends ILRD if this option is enabled for your application.
```

### Initialize CAS SDK

Source: https://production.docs.page/docs/flutter/initialize-cas

```mdx

Before loading ads, have your app initialize CAS Mobile Ads SDK by calling [CASMobileAds.initialize()](https://pub.dev/documentation/clever_ads_solutions/latest/clever_ads_solutions/CASMobileAds/initialize.html) which initializes the SDK and returns a `Future` that finishes once initialization is complete. 

The `casId` is a unique identifier for the CAS content registered for your app on each platform.  
You can use the value `demo` to force test ads mode on all devices if you haven't registered a `casId` yet.

```dart
import 'package:clever_ads_solutions/clever_ads_solutions.dart';
  
void main() {  

  String casId = Platform.isAndroid ? 'demo' : 'demo';
  
  CASMobileAds.initialize(  
    casId: casId,  
  ).then((InitializationStatus status) {  
    if (status.error != null) {  
      print('CAS Mobile Ads SDK initialization failed: ${status.error}');  
    } else {  
      print('CAS Mobile Ads SDK initialized in ${status.countryCode} country');  
    }  
  });  
  
  runApp(const MyApp());  
}
```

If `initialize()` method is not called, the first ad load automatically initializes the CAS Mobile Ads SDK with CAS Id defined in ad load arguments.

If an error occurs, the SDK will attempt automatic reinitialization internally. However, the `Future` will not be updated with subsequent `InitializationStatus`. For the most up-to-date `InitializationStatus`, call `initialize()` method again at a later time.

<Error>  
Do not initialize mediated advertising SDKs (CAS does that for you).  
Not following this step will result in noticeable integration issues.
</Error>

## Automatic user consent flow
To get consent for collecting personal data of your users, we suggest you use a built-in Consent Flow, comes with a pre-made consent form that you can easily present to your users. That means you no longer need to create your own consent window.

The user will see the consent flow when your app initializes the CAS SDK.  
Once the user completes the flow, the `initialize` `Future` will complete.

You can choose whether to `showConsentFormIfRequired` in the arguments of the `initialize()` method:
```dart
  CASMobileAds.initialize(  
    casId: casId,  
    showConsentFormIfRequired: true, // [!code highlight]
    ...
  ).then((InitializationStatus status) {  
    if (status.consentFlowStatus == ConsentFlow.statusObtained) {  
      print('CAS Mobile Ads SDK obtain user consent');  
    } 
  });  
```

You must wait until the user finishes the consent flow before you initialize third-party SDKs (such as MMPs or analytics SDKs). For this reason, initialize such SDKs from within your initialization-completion callback. If you were to initialize these third-party SDKs before the user completes the consent flow, these third-party SDKs would not be able to access relevant identifiers and you would suffer a material impact on measurement, reporting, and ad revenue.

<Info>
Read more about "Privacy options button" and "Debug geography" on [CAS User Consent Flow page](flutter/user-consent-flow)
</Info>

## Always test with test ads
When building and testing your apps, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account.

By default, CAS initializes mediation in live mode. To enable test ad mode, you should manually set `forceTestAds` in the arguments of the `initialize()` method:
```dart
  CASMobileAds.initialize(  
    casId: casId,  
    forceTestAds: kDebugMode || kProfileMode, // [!code highlight]
    testDeviceIds: [
        'Your test device ID' // [!code highlight]
    ],
    ...
  )
```

You can also test in release build by registering your device as a test device. Check the logs for your device's ID value.

For more information about how the CAS.AI SDK's test ads work, see [Enable test ads](flutter/enabling-test-ads)

## Prohibition on Personal Information from Children
Apps can be marked as child-directed or [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy) applicable through the CAS UI.  

If the app has knowledge of specific individuals as being COPPA-applicable, it should make use of the `targetAudience`parameter in the `initialize()` function.
```dart
  CASMobileAds.initialize(  
    casId: casId,  
    audience: Audience.notChildren, // [!code highlight]
    ...
  )
```

If your app targets both children and older users, all ads that may be shown to children must comply with COPPA.  
To ensure compliance, a **neutral age screen** must be implemented so that ads unsuitable for children are only shown to appropriate audiences.  
A neutral age screen is a tool—such as an age gate—that verifies a user’s age without encouraging them to misrepresent it, and prevents children from accessing content not intended for them.

## (Optional) Retrieve the Version Number
To programmatically retrieve the SDK version number at runtime, CAS provides the following method:
```dart
String sdkVersion = await CAS.getSDKVersion();
```

## (Optional) Trial ad-free interval
Defines the time interval, in seconds, starting from the moment of the initial app installation, during which users can use the application without ads being displayed while still retaining access to the Rewarded Ads format. Within this interval, users enjoy privileged access to the application's features without intrusive advertisements.  

```dart
int secondsIn7Days = 604800;
CASMobileAds.setTrialAdFreeInterval(secondsIn7Days);
```

## Complete example
- [Initialize CASMobileAds example](https://github.com/cleveradssolutions/CAS-Flutter/blob/main/example/lib/main.dart)
```

### Interstitial Ads

Source: https://production.docs.page/docs/flutter/interstitial-ads

```mdx

Interstitial ads are full-screen ads that cover the interface of their host app. 
They're typically displayed at natural transition points in the flow of an app, such as between screens. 
When an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.

Interstitial Ad management in Dart code is handled through the [CASInterstitial](https://pub.dev/documentation/clever_ads_solutions/latest/clever_ads_solutions/CASInterstitial-class.html) class, 
which extends the shared `AdScreenInstance` class used for all fullscreen ads. 
The `AdScreenInstance` class, inherits from the base `AdInstance` class, which is common for all CAS ad formats. 
The `AdScreenInstance` is displayed as an `Overlay` on top of all app content and is positioned statically; 
therefore, it cannot be added to the Flutter widget tree.

CAS provides an option to enable `autoReload` to simplify your app logic. Before using the ad, you should decide whether to enable `autoReload`, or manually manage each ad loading cycle in your code. 

When `autoReload` is enabled, a new ad will be automatically loaded after each display, and loading failures will trigger automatic retry attempts. 
```dart
final bool isAutoReloadEnabled = true;
```

Manual load mode (`autoReload: false` ) is useful when you only need to show a single ad per app screen, and the screens change frequently.  

Below is a diagram showing the ad lifecycle and how `autoReload` (isAutoload) affects it.

<Image zoom src="/assets/Lifecycle-Screen-Ad.png" alt="Diagram" height="500" />


## Create Ad instance
The following example creates and loads an interstitial ad:
```dart
class AppScreenState extends State<AppScreen> {
  late CASInterstitial _interstitialAd;
  
  @override
  void initState() {
    super.initState();
    
    _interstitialAd = CASInterstitial.createAndLoad( 
      autoReload: isAutoReloadEnabled, 
      onAdLoaded: (AdScreenInstance ad) { 
        // Called when an ad is successfully loaded. 
        print('$ad loaded');  
      },  
      onAdFailedToLoad: (AdInstance ad, AdError error) { 
        // Called when an ad load failed. 
        print('$ad failed to load: ${error.message}.'); 
      }, 
    ); 
  }
}
```

Ad content may take some time to load after creating an ad instance. To ensure the ad displays instantly when needed, create the ad instance in advance. Use the `onAdLoaded` callback to be notified when the ad is ready for display.

## Ad content callbacks
`CASInterstitial` has several optional callbacks for the ad lifecycle. These callbacks can be set either as arguments in the `createAndLoad()` function or later via the properties of the ad instance.

```dart
_interstitialAd.onAdFailedToShow = (AdInstance ad, AdError error) { 
  // Called when the ad failed to show full screen content. 
  print('$ad failed to show: ${error.message}.');  
};  
_interstitialAd.onAdShowed = (AdScreenInstance ad) {  
  // Called when the ad showed the full screen content.
  print('$ad showed');  
};  
_interstitialAd.onAdImpression = (AdInstance ad, AdContentInfo contentInfo) { 
  // Called when an impression occurs on the ad. 
  print('$ad impression');  
};  
_interstitialAd.onAdClicked = (AdInstance ad) {  
  // Called when a click is recorded for an ad.
  print('$ad clicked');  
};  
_interstitialAd.onAdDismissed = (AdScreenInstance ad) { 
  // Called when the ad dismissed full screen content. 
  print('$ad dismissed');  
};
```

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](flutter/impression-level-data).
- When an error occurs during ad impression, executed the `onAdFailedToShow` only.  In this case the `onAdDismissed` will not be executed, since the impression is not considered successful.
</Info>

## Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.

```dart
_interstitialAd = CASInterstitial.createAndLoad( 
  placement: "BestPlace", // [!code highlight]
)
```

## Show Ad
Interstitial ads should be displayed during natural pauses in the flow of an app. Between app screens is a good example, or after the user completes a task. 

You can choose when to show the ad by calling `show()`:
```dart
_interstitialAd.show();
```

If the ad is not ready at that moment, the `onAdFailedToShow` callback will be triggered with a reason provided in the `AdError`.

You have the option to check `isLoaded` if it's required by your app's logic.
```dart
bool isAdLoaded = await _interstitialAd.isLoaded();
```

### Auto Show Ad mode
CAS provides the option to automatically show a loaded ad when the user returns to the app. To enable this behavior, set the `autoShow` argument to `true`.
```dart
_interstitialAd = CASInterstitial.createAndLoad(
  autoShow: true, // [!code highlight]
  ...
)
```

## Release ad resource
Be sure to release ad resources if you’re no longer going to use the ad instance.
```dart
  @override
  void dispose() {
    _interstitialAd.dispose(); // [!code highlight]
    super.dispose();
  }
```
It may be useful to store the ad instance in static memory for reuse across multiple screens. This way, you don't need to call `dispose()` and can show the already loaded ad without delay.

## Manual reload Ad
When you want to manually control ad loading, use the `load()` function on the created ad instance to retry loading with the same configuration.
```dart
_interstitialAd.load();
```

## Minimum interval between impressions
The minimum interval between showing interstitial ads, in seconds.  
Attempting to show a new interstitial ad before the interval has passed after the previous one was dismissed will trigger `onAdFailedToShow` with `AdError.codeNotPassedInterval`.

```dart
_interstitialAd = CASInterstitial.createAndLoad(
  minInterval: 0, // [!code highlight]
  ...
)
```

Note that the timer for the minimum interval is shared across all interstitial ad instances, but the minimum interval value may differ for each ad instance.

If you need to reset the minimum interval timer after showing a Rewarded Ad or an AppOpen Ad, you can call the `_interstitialAd.restartInterval()` method in the `onAdDismissed` callback for these ad formats.

## Mute Ad sounds
Indicates if the application’s audio is muted. Affects initial mute state for fullscreen ads. Use this method only if your application has its own volume controls (e.g., custom music or sound effect muting).
```dart
CASMobileAds.setAdSoundsMuted(true);
```
Not muted by default.

## Some best practices
#### Consider whether interstitial ads are the right type of ad for your app.
Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, like sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it's easy to present an interstitial ad without disrupting their experience. Make sure you consider at which points in your app's workflow you'll display interstitial ads and how the user is likely to respond.

#### Remember to pause the action when displaying an interstitial ad.
There are a number of different types of interstitial ads: text, image, video, and more. It's important to make sure that when your app displays an interstitial ad, it also suspends its use of some resources to allow the ad to take advantage of them. For example, when you make the call to display an interstitial ad, be sure to pause any audio output being produced by your app.

#### Allow for adequate loading time.
Just as it's important to make sure you display interstitial ads at an appropriate time, it's also important to make sure the user doesn't have to wait for them to load. Loading the ad in advance by calling `load()` before you intend to call `show()` can ensure that your app has a fully loaded interstitial ad at the ready when the time comes to display one.

#### Don't flood the user with ads.
While increasing the frequency of interstitial ads in your app might seem like a great way to increase revenue, it can also degrade the user experience and lower clickthrough rates. Make sure that users aren't so frequently interrupted that they're no longer able to enjoy the use of your app.

## Complete example
- [Interstitial ad example](https://github.com/cleveradssolutions/CAS-Flutter/blob/main/example/lib/main.dart#L131)
```

### Native Ads

Source: https://production.docs.page/docs/flutter/native-ads

```mdx

Native ads are ad assets presented to users with UI components native to the platform. In coding terms, this means that when a native ad loads, your app receives a `NativeAdContent` object that contains its assets, and your app is then responsible for displaying them. Additionally, these ads can be customized to align with your app's visual design, ensuring they feel like a natural part of the content rather than intrusive advertisements.

Native Ad management in Dart code is handled through the [CASNativeContent](https://pub.dev/documentation/clever_ads_solutions/latest/clever_ads_solutions/CASNativeContent-class.html) class, which extends the shared `AdViewInstance` class used for all ads displayed in a widgets. The `AdViewInstance` class, inherits from the base `AdInstance` class, which is common for all CAS ad formats. To display a `AdViewInstance` as a widget, you must instantiate an `CASWidget` for each ad instance. 

There are two ways to build native ads view in Flutter app:
#### 1. Native templates 
Native templates are code-complete views for your native ads, designed for fast implementation and easy modification. With native templates, the plugin provides prebuilt Android and iOS layouts for you, and you can customize the style of the native assets using a Dart API.

For native templates implementation details in Dart, see [Native templates](flutter/native-ads-templates) page.

#### 2. Platform setup 
Custom platform-specific layouts defined using Android and iOS layout tools.  
Platform setup is better when you need complete control of the look and feel for your ads on both Android and iOS platforms, but you'll need to write code for both.

For platform-specific setup instructions, see [Android setup](flutter/native-ads-android-setup) and [iOS setup](flutter/native-ads-ios-setup) pages.

## Load Ad content
The following example loads an native ad content.
- The `adChoicesPlacement` option specifies where to place the AdChoices icon.
- The `startVideoMuted` option controls whether the video content starts muted or unmuted.
- Use the `onAdLoaded` callback to be notified when the ad is ready for display.
- The remaining callbacks are optional and can be implemented as needed.
```dart
class NativeAdExampleState extends State<NativeAdExample> {
  AdViewInstance? _nativeAd;
  
  void _loadAd() {
    CASNativeContent.load( 
      adChoicesPlacement: AdChoicesPlacement.topRightCorner,  
      startVideoMuted: true,
      onAdLoaded: (AdViewInstance ad) { 
        // Called when an ad is successfully loaded. 
        print('$ad loaded');  
        setState(() { 
          _nativeAd = ad;
        });
      },  
      onAdFailedToLoad: (AdInstance ad, AdError error) { 
        // Called when an ad load failed. 
        print('$ad failed to load: ${error.message}.'); 
      }, 
      onAdImpression: (AdInstance ad, AdContentInfo contentInfo) { 
        // Called when an impression occurs on the ad.  
        print('$ad impression');  
      },  
      onAdClicked: (AdInstance ad) {  
        // Called when a click is recorded for an ad.
        print('$ad clicked');  
      },
    ); 
  }
}
```

<Info>
Read more about `AdContentInfo` structure in [Impression Level Data](flutter/impression-level-data).
</Info>

## Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.

```dart
CASNativeContent.load( 
  placement: "BestPlace", // [!code focus] 
)
```

## Show Ad Widget
`CASWidget` inherits from Flutter's Widget class and can be used like any other widget.  
Ensure that you define the desired widget size, as native ads do not have an intrinsic size and will expand to fit the constraints of their container. You may provide a fixed size or use `LayoutBuilder` to dynamically allocate space for the ad.
```dart
@override  
Widget build(BuildContext context) {  
  return LayoutBuilder(  
    builder: (BuildContext context, BoxConstraints constraints) {  
      if (_nativeAd != null) {  
        return CASWidget(  
          ad: _nativeAd!,  
          width: constraints.maxWidth,  
          height: 400,  
        );  
      }  
      return const Text("Ad Loading...");  
    },  
  );  
}
```
Native ads do not require reloading when the widget size changes, the content will automatically adapt to the new size.

## Release ad resource
Be sure to release ad resources if you’re no longer going to use the ad instance.
```dart
  @override
  void dispose() {
    _nativeAd?.dispose();
    super.dispose();
  }
```

## Complete example
- [Native Ad Template example](https://github.com/cleveradssolutions/CAS-Flutter/tree/main/example/lib/native_template_example.dart)
- [Native Ad Factory example](https://github.com/cleveradssolutions/CAS-Flutter/tree/main/example/lib/native_factory_example.dart)
```

### Native Ads Android Setup

Source: https://production.docs.page/docs/flutter/native-ads-android-setup

```mdx

Native ads are presented to users using UI components native to the platform: a `View` on Android or a `UIView` on iOS.

<Steps>
<Step title="Import the CASMobileAdsPlugin class">
The Android implementation of the CAS Mobile Ads plugin requires a class implementing the`NativeAdFactory` API. In order to reference this API from your Android project, add the following lines to your `android/settings.gradle`:
```groovy
def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
if (pluginsFile.exists()) {
    pluginsFile.withInputStream { stream -> plugins.load(stream) }
}

plugins.each { name, path ->
    def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
    include ":$name"
    project(":$name").projectDir = pluginDirectory
}
```
</Step>
<Step title="Layout the views">
Navigate to `<project>/android/app/main/res/layout` and create a new XML layout file.

The view hierarchy for a native ad that uses a `CASNativeView` to display its asset views might look like this:
```xml
<com.cleveradssolutions.sdk.nativead.CASNativeView
    xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout android:orientation="vertical">
        <LinearLayout android:orientation="horizontal">
            <ImageView android:id="@+id/ad_icon" />
            <TextView android:id="@+id/ad_headline" />
            <com.cleveradssolutions.sdk.nativead.CASChoicesView
                android:id="@+id/ad_choices_view" />
        </LinearLayout>
        <com.cleveradssolutions.sdk.nativead.CASMediaView
            android:id="@+id/ad_media_view" />
        <com.cleveradssolutions.sdk.nativead.CASStarRatingView
            android:id="@+id/ad_star_rating" />

        <!-- Other assets such as image or call to action, etc follow. -->
    </LinearLayout>
</com.cleveradssolutions.sdk.nativead.CASNativeView>
```

<Success>
For an example of configuring your `CASNativeAdView` layout, see [native_ad_layout.xml](https://github.com/cleveradssolutions/CAS-Flutter/tree/main/example/android/app/src/main/res/layout/native_ad_layout.xml).
</Success>

<Info>
Note that all asset views for a given native ad should be rendered inside the `CASNativeView` layout.  
Please review the description and requirements of native ad assets on [CAS Android page](android/native-ad-assets).
</Info>
</Step>

<Step title="Implement Native Ad Factory">
Navigate to `<project>/android/app/main` and create a new class that implements the `CASNativeAdViewFactory`interface. Override the `createNativeAdView` function, in which you need to create and return the `CASNativeView`. 

Register all the view assets you use in the layout to the `adView`, and the CAS SDK will automatically populate them with ad content, or make the view invisible if the corresponding asset is not provided in the ad content.

```kotlin
import android.content.Context  
import android.view.LayoutInflater  
import com.cleveradssolutions.plugin.flutter.CASMobileAdsPlugin  
import com.cleveradssolutions.plugin.flutter.CASNativeAdViewFactory  
import com.cleveradssolutions.sdk.nativead.CASNativeView  
import com.cleveradssolutions.sdk.nativead.NativeAdContent

class NativeAdFactoryExample : CASNativeAdViewFactory {  
    override fun createNativeAdView(  
        context: Context,  
        nativeAd: NativeAdContent,  
        customOptions: Map<String, Any?>  
    ): CASNativeView? {  
        val adView = LayoutInflater.from(context).inflate(  
            R.layout.native_ad_layout, null, false  
        ) as CASNativeView  
  
        adView.mediaView = adView.findViewById(R.id.ad_media_view)  
        adView.adLabelView = adView.findViewById(R.id.ad_label)  
        adView.headlineView = adView.findViewById(R.id.ad_headline)  
        adView.iconView = adView.findViewById(R.id.ad_icon)  
        adView.callToActionView = adView.findViewById(R.id.ad_call_to_action)  
        adView.bodyView = adView.findViewById(R.id.ad_body)  
        adView.advertiserView = adView.findViewById(R.id.ad_advertiser)  
        adView.storeView = adView.findViewById(R.id.ad_store)  
        adView.priceView = adView.findViewById(R.id.ad_price)  
        adView.reviewCountView = adView.findViewById(R.id.ad_review_count)  
        adView.starRatingView = adView.findViewById(R.id.ad_star_rating)  
  
        return adView  
    }  
}
```
The CAS Flutter plugin will automatically call `adView.bindAdContent(nativeAd)` later in any case.

You can find more details about the implementation of platform native ad view on the [CAS Android page](android/display-native-ad#manual-display-native-ad).
</Step>

<Step title="Register Native Ad Factory in CAS Plugin">
Each `CASNativeAdViewFactory` implementation is required to be registered with a `factoryId`, a unique `String` identifier, when calling `configureFlutterEngine()`. The `factoryId` will be used later when loading a native ad from Dart code.

A `CASNativeAdViewFactory` can be implemented and registered for each unique native ad layout used by your app, or a single one can handle all layouts.

Note that when building with [add-to-app](https://flutter.dev/docs/development/add-to-app#add-to-app), the `NativeAdFactory` should also be unregistered in`cleanUpFlutterEngine()`.

Once you've created `NativeAdFactoryExample`, set up your`FlutterActivity` as follows:
```kotlin
import com.cleveradssolutions.plugin.flutter.CASMobileAdsPlugin 

class MainActivity : FlutterActivity() {  
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {  
        super.configureFlutterEngine(flutterEngine)  
  
        CASMobileAdsPlugin.nativeAdFactories = mapOf( // [!code highlight]
            "nativeFactoryIdExample" to NativeAdFactoryExample() // [!code highlight]  
        ) // [!code highlight]
    }  
  
    override fun cleanUpFlutterEngine(flutterEngine: FlutterEngine) {  
        super.cleanUpFlutterEngine(flutterEngine)  
  
        CASMobileAdsPlugin.nativeAdFactories = null // [!code highlight]
    }  
}
```
</Step>

<Step title="Load ad content with factory ID">
After you've added your platform-specific code, turn to Dart to load ads. 
- Make sure `factoryId` match the ID you registered earlier.
- `сustomOptions` are optional parameters for creating your native ad view. These parameters will be passed as a `Map` to the ad view creation function on both Android and iOS.

```dart
class NativeAdExampleState extends State<NativeAdExample> {
  AdViewInstance? _nativeAd;
  
  void _loadAd() {
    CASNativeContent.load( 
      factoryId: 'nativeFactoryIdExample', // [!code highlight]  
      customOptions: {  
        'exampleOptionKey': 'exampleValue', // [!code highlight]  
      },
      onAdLoaded: (AdViewInstance ad) { 
        // Called when an ad is successfully loaded. 
        print('$ad loaded'); 
        setState(() { 
          _nativeAd = ad;
        });
      },  
    );
  }
}
```
</Step>
<Step title="Continue to use Native Ad as usual"/>
</Steps>
```

### Native Ads iOS Setup

Source: https://production.docs.page/docs/flutter/native-ads-ios-setup

```mdx

Native ads are presented to users using UI components native to the platform: a `View` on Android or a `UIView` on iOS.

<Steps>
<Step title="Layout the views">
The first step is to lay out the `UIViews` that will display native ad assets. You can do this in the Xcode Interface Builder as you would when creating any other xib file. Create a new View `xib` file in `ios` project.

Set Custom Class value to `CASNativeView`. This is the ad view class that is used to display a `NativeAdContent`.

<Image width="257" alt="Image" src="/assets/ios/Native-NativeView.png" />

You'll also need to set the custom class for the `CASMediaView`, which is used to display the video or image for the ad.

<Image width="262" alt="Image" src="/assets/ios/Native-MediaView.png" />

Assign unique tag IDs to the asset views. The example image below sets the ID to `100` for the Media View.

<Image width="298" alt="Image" src="/assets/ios/Native-ViewTags.png" />

<Success>  
For an example of configuring your `CASNativeAdView` layout, see [NativeAdView.xib](https://github.com/cleveradssolutions/CAS-Flutter/tree/main/example/ios/Runner/NativeAdView.xib).
</Success>

<Info>
Note that all asset views for a given native ad should be rendered inside the `CASNativeView` layout.  
Please review the description and requirements of native ad assets on [CAS iOS page](ios/native-ad-assets).
</Info>
</Step>

<Step title="Implement Native Ad Factory">
Create a new class that implements the `CASNativeAdViewFactory`protocol from `clever_ads_solutions` module. Implement the `createNativeAdView` function, in which you need to create and return the `CASNativeView`. 

Register all the views by tag ID you use in the layout to the `adView`, and the CAS SDK will automatically populate them with ad content, or make the view invisible if the corresponding asset is not provided in the ad content.

```swift
import clever_ads_solutions // CAS Flutter module
import CleverAdsSolutions // CAS iOS SDK
import Foundation

class NativeAdFactoryExample: NSObject, CASNativeAdViewFactory {
    func createNativeAdView(for adContent: NativeAdContent,
                            customOptions: [String: Any]) -> CASNativeView? {
        let adView = Bundle.main.loadNibNamed(
            "NativeAdView", owner: nil
        )!.first as! CASNativeView

        adView.registerMediaView(tag: 100)
        adView.registerIconView(tag: 101)
        adView.registerHeadlineView(tag: 102)
        adView.registerAdLabelView(tag: 103)
        adView.registerBodyView(tag: 104)
        adView.registerCallToActionView(tag: 105)
        adView.registerAdvertiserView(tag: 106)
        adView.registerStoreView(tag: 107)
        adView.registerPriceView(tag: 108)
        adView.registerStarRatingView(tag: 109)
        adView.registerReviewCountView(tag: 110)

        return adView
    }
}
```
The CAS Flutter plugin will automatically call `adView.bindAdContent(nativeAd)` later in any case.

You can find more details about the implementation of platform native ad view on the [CAS iOS page](ios/display-native-ad#manual-display-native-ad).
</Step>

<Step title="Register Native Ad Factory in CAS Plugin">
Each `CASNativeAdViewFactory` implementation is required to be registered with a `factoryId`, a unique `String` identifier, when calling `application(_:didFinishLaunchingWithOptions:)`. The `factoryId` will be used later when loading a native ad from Dart code.

A `CASNativeAdViewFactory` can be implemented and registered for each unique native ad layout used by your app, or a single one can handle all layouts.

Once you've created `NativeAdFactoryExample`, set up your`AppDelegate` as follows:
```swift
import clever_ads_solutions
import Flutter
import UIKit

@main
@objc class AppDelegate: FlutterAppDelegate {
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)

        // Register map of NativeAdFactory to CAS Flutter Plugin
        CASMobileAdsPlugin.nativeAdFactories = [ // [!code highlight]
            "nativeFactoryIdExample": NativeAdFactoryExample(), // [!code highlight]
        ] // [!code highlight]

        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
```
</Step>

<Step title="Load ad content with factory ID">
After you've added your platform-specific code, turn to Dart to load ads. 
- Make sure `factoryId` match the ID you registered earlier.
- `сustomOptions` are optional parameters for creating your native ad view. These parameters will be passed as a `Map` to the ad view creation function on both Android and iOS.

```dart
class NativeAdExampleState extends State<NativeAdExample> {
  AdViewInstance? _nativeAd;
  
  void _loadAd() {
    CASNativeContent.load( 
      factoryId: 'nativeFactoryIdExample', // [!code highlight]  
      customOptions: {  
        'exampleOptionKey': 'exampleValue', // [!code highlight]  
      },
      onAdLoaded: (AdViewInstance ad) { 
        // Called when an ad is successfully loaded. 
        print('$ad loaded'); 
        setState(() { 
          _nativeAd = ad;
        });
      },  
    );
  }
}
```
</Step>

<Step title="Continue to use Native Ad as usual"/>
</Steps>
```

### Native Ads templates

Source: https://production.docs.page/docs/flutter/native-ads-templates

```mdx

Native templates are code-complete views for your native ads, designed for fast implementation and easy modification. With native templates, the plugin provides prebuilt Android and iOS layouts for you, and you can customize the style of the native assets using a Dart API.

By default, if no `factoryId` is specified when loading a native ad, the standard CAS Template will be used to display the native ad content. Below is an example of how the CAS Template appears depending on the size of the `CASWidget`.

1. If the height is greater than 500, a large native ad layout is used.
<Image height="500" alt="Image" src="/assets/Native-Template-Screen.jpg" />

2. If the height is greater than 200, a medium layout is used.
<Image width="300" alt="Image" src="/assets/Native-Template-MRec.jpg" />

3. Otherwise, a banner layout is used.
<Image width="300" alt="Image" src="/assets/Native-Template-Small.jpg" />

## Customize ad
The CAS Template can be customized by changing the colors of individual components and the font style using `NativeTemplateStyle` parameters when loading a native ad in Dart code.

- The background color.  
- The primary color for "Call to action" button background.  
- The text color for "Call To Action" button.  
- The Headline text color.  
- The Headline text font style.  
- The Secondary (other) text color.  
- The Secondary (other) text font style.  

## Load ad content
The following example loads a native ad using the `NativeTemplateStyle` with the default configuration:
```dart
class NativeAdExampleState extends State<NativeAdExample> {
  AdViewInstance? _nativeAd;
  
  void _loadAd() {
    CASNativeContent.load( 
      factoryId: 'nativeFactoryIdExample',  
        templateStyle: NativeTemplateStyle(  
        backgroundColor: Colors.white,  
        primaryColor: Colors.blueAccent,  
        primaryTextColor: Colors.white,  
        headlineTextColor: Colors.black,  
        headlineFontStyle: NativeTemplateFontStyle.bold,  
        secondaryTextColor: Colors.black12,  
        secondaryFontStyle: null,  
      ),
      onAdLoaded: (AdViewInstance ad) { 
        // Called when an ad is successfully loaded. 
        print('$ad loaded'); 
        setState(() { 
          _nativeAd = ad;
        });
      },  
    );
  }
}
```

**Continue to use Native Ad as usual.**
```

### Purchase Info

Source: https://production.docs.page/docs/flutter/purchase-info

```mdx

The `CASPurchaseInfo` class is used to report in-app purchases to CAS.AI. Along with the SDK's ad revenue tracking, this allows you to get a complete picture of a user's total value by combining ad revenue and IAP revenue in one place.

The total reported revenue is calculated as:

```
revenue = quantity * price * currency_rate
```

## Reporting a purchase

Call `CASMobileAds.reportPurchase(...)` with a `CASPurchaseInfo` object as soon as you've confirmed a completed transaction.

The steps below use the [`in_app_purchase`](https://pub.dev/packages/in_app_purchase) plugin, where `details` is a `PurchaseDetails` with the `PurchaseStatus.purchased` status received from `InAppPurchase.instance.purchaseStream`, and `product` is the `ProductDetails` it was bought from. Report the purchase before you finish it with `InAppPurchase.instance.completePurchase(details)`.

### 1. Create `CASPurchaseInfo`

Build the object from the product id, price, currency and quantity.

```dart
final purchase = CASPurchaseInfo(
  productId: details.productID,
  price: product.rawPrice,
  currency: product.currencyCode,
);
```

<Info>
The `in_app_purchase` plugin does not expose the purchased quantity of a Google Play purchase, so `quantity` defaults to `1`. For a StoreKit 1 transaction you can pass `details.skPaymentTransaction.payment.quantity`.
</Info>

### 2. Recommended: attach validation data

Add the validation data of the transaction so CAS.AI can verify the purchase server-side. The data lives on the store specific `PurchaseDetails` subclass, so check the type of `details`:

<Tabs groupId="platform">
<TabItem label="Android" value="android">
`GooglePlayPurchaseDetails` comes from `package:in_app_purchase_android/in_app_purchase_android.dart`.

```dart
if (details is GooglePlayPurchaseDetails) {
  final googlePurchase = details.billingClientPurchase;
  purchase.setGoogleValidation(
    originalJson: googlePurchase.originalJson,
    signature: googlePurchase.signature,
  );
}
```
</TabItem>

<TabItem label="iOS" value="ios">
`SK2PurchaseDetails` and `AppStorePurchaseDetails` come from `package:in_app_purchase_storekit/in_app_purchase_storekit.dart`. Which one you get depends on the StoreKit version the plugin runs on, so handle both.

```dart
if (details is SK2PurchaseDetails) {
  // StoreKit 2: the server verification data is the JWS representation
  purchase.setAppleValidation(
    transactionId: details.purchaseID,
    jwsRepresentation: details.verificationData.serverVerificationData,
  );
} else if (details is AppStorePurchaseDetails) {
  // StoreKit 1: the local verification data is the base64 encoded app receipt
  purchase.setAppleValidation(
    transactionId: details.skPaymentTransaction.transactionIdentifier,
    receiptBase64: details.verificationData.localVerificationData,
  );
}
```
</TabItem>
</Tabs>

<Info>
Validation data is optional, but it is recommended when available.
</Info>

### 3. If the product is a subscription

Neither Google Play Billing nor StoreKit reports whether a product is a subscription on the transaction itself. That comes from your own product catalog, for example from the `ProductDetails` you fetched when querying the products, or however you classify product ids on your side. Check that first, then attach the subscription data:

<Tabs groupId="platform">
<TabItem label="Android" value="android">
```dart
purchase.setGoogleSubscription(
  purchaseToken: googlePurchase.purchaseToken,
  purchaseTime: googlePurchase.purchaseTime,
);
```
</TabItem>

<TabItem label="iOS" value="ios">
```dart
purchase.setAppleSubscription(
  jsonRepresentation: details.verificationData.localVerificationData,
);
```
</TabItem>
</Tabs>

<Info>
`setAppleSubscription` called without arguments reads the subscription data from the current StoreKit entitlement of the product, which requires iOS 16.0 or higher. Use it for StoreKit 1 transactions, where the json representation is not available.
</Info>

### 4. Report

With the product info, validation and, if applicable, subscription data attached, `purchase` is ready to send:

```dart
await CASMobileAds.reportPurchase(purchase);
```

## Complete example

```dart
import 'package:clever_ads_solutions/clever_ads_solutions.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_android/in_app_purchase_android.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';

// The products of your catalog, by product id, from queryProductDetails().
Map<String, ProductDetails> _products = {};

void _onPurchaseUpdated(List<PurchaseDetails> purchases) {
  for (final details in purchases) {
    if (details.status != PurchaseStatus.purchased) continue;

    final product = _products[details.productID];
    if (product != null) {
      _reportPurchase(details, product);
    }

    if (details.pendingCompletePurchase) {
      InAppPurchase.instance.completePurchase(details);
    }
  }
}

void _reportPurchase(PurchaseDetails details, ProductDetails product) {
  final purchase = CASPurchaseInfo(
    productId: details.productID,
    price: product.rawPrice,
    currency: product.currencyCode,
  );

  // Your own classification of the product, CAS.AI cannot derive it
  // from the transaction.
  final isSubscription = _isSubscription(details.productID);

  if (details is GooglePlayPurchaseDetails) {
    final googlePurchase = details.billingClientPurchase;
    purchase.setGoogleValidation(
      originalJson: googlePurchase.originalJson,
      signature: googlePurchase.signature,
    );
    if (isSubscription) {
      purchase.setGoogleSubscription(
        purchaseToken: googlePurchase.purchaseToken,
        purchaseTime: googlePurchase.purchaseTime,
      );
    }
  } else if (details is SK2PurchaseDetails) {
    purchase.setAppleValidation(
      transactionId: details.purchaseID,
      jwsRepresentation: details.verificationData.serverVerificationData,
    );
    if (isSubscription) {
      purchase.setAppleSubscription(
        jsonRepresentation: details.verificationData.localVerificationData,
      );
    }
  } else if (details is AppStorePurchaseDetails) {
    purchase.setAppleValidation(
      transactionId: details.skPaymentTransaction.transactionIdentifier,
      receiptBase64: details.verificationData.localVerificationData,
    );
    if (isSubscription) {
      purchase.setAppleSubscription();
    }
  }

  CASMobileAds.reportPurchase(purchase);
}
```

## Other IAP providers

Google Play Billing and the Apple App Store are the providers of the platform stores, but a purchase may be processed elsewhere. Use the matching validation method and `CASPurchaseInfo` is reported for that provider instead:

```dart
// Amazon Appstore, with the receipt id and the user id of the receipt
purchase.setAmazonValidation(receiptId: receiptId, userId: userId);

// Amazon Appstore, with the JSON string of the receipt
purchase.setAmazonValidationFromReceipt(receipt);

// Xsolla
purchase.setXsollaValidation(orderId: orderId, userId: userId);
```

<Warning>
For these providers the purchase price, currency and quantity are your responsibility, for example from your own product catalog or pricing configuration, so that revenue is reported accurately.
</Warning>

## Automatic forwarding to Tenjin

Purchases reported through `CASMobileAds.reportPurchase(...)` can also be forwarded automatically to Tenjin Analytics, so you don't need a separate integration to get IAP revenue into Tenjin.

<Info>
This requires CAS SDK 4.8.1 or higher, and the feature must be enabled for your account. Contact your account manager to request it.
</Info>
```

### Rewarded Ads

Source: https://production.docs.page/docs/flutter/rewarded-ads

```mdx

Rewarded ads let you offer users in-app items, such as continued gameplay, virtual currency, or other rewards, in exchange for their engagement with ads. 
Rewarded ads boost engagement because users receive a tangible benefit for their time.

Rewarded Ad management in Dart code is handled through the [CASRewarded](https://pub.dev/documentation/clever_ads_solutions/latest/clever_ads_solutions/CASRewarded-class.html) class, 
which extends the shared `AdScreenInstance` class used for all fullscreen ads. 
The `AdScreenInstance` class, inherits from the base `AdInstance` class, which is common for all CAS ad formats. 
The `AdScreenInstance` is displayed as an `Overlay` on top of all app content and is positioned statically; 
therefore, it cannot be added to the Flutter widget tree.

CAS provides an option to enable `autoReload` to simplify your app logic. Before using the ad, you should decide whether to enable `autoReload`, or manually manage each ad loading cycle in your code. 

When `autoReload` is enabled, a new ad will be automatically loaded after each display, and loading failures will trigger automatic retry attempts. 
```dart
final bool isAutoReloadEnabled = true;
```

Manual load mode (`autoReload: false` ) is useful when you only need to show a single ad per app screen, and the screens change frequently.  

Below is a diagram showing the ad lifecycle and how `autoReload` (isAutoload) affects it.

<Image zoom src="/assets/Lifecycle-Rewarded-Ad.png" alt="Diagram" height="500" />


## Create Ad instance
The following example creates and loads an rewarded video ad:
```dart
class AppScreenState extends State<AppScreen> {
  late CASRewarded _rewardedAd;
  
  @override
  void initState() {
    super.initState();
    
    _rewardedAd = CASRewarded.createAndLoad( 
      autoReload: isAutoReloadEnabled, 
      onAdLoaded: (AdScreenInstance ad) { 
        // Called when an ad is successfully loaded. 
        print('$ad loaded');  
      },  
      onAdFailedToLoad: (AdInstance ad, AdError error) { 
        // Called when an ad load failed. 
        print('$ad failed to load: ${error.message}.'); 
      }, 
    ); 
  }
}
```

Ad content may take some time to load after creating an ad instance. To ensure the ad displays instantly when needed, create the ad instance in advance. Use the `onAdLoaded` callback to be notified when the ad is ready for display.

CAS provides functionality to create and preload multiple ad instances in advance, ensuring uninterrupted sequential ad delivery. Mediation ads are loaded in order for each created instance.

## Ad content callbacks
`CASRewarded` has several optional callbacks for the ad lifecycle. These callbacks can be set either as arguments in the `createAndLoad()` function or later via the properties of the ad instance.

```dart
_rewardedAd.onAdFailedToShow = (AdInstance ad, AdError error) { 
  // Called when the ad failed to show full screen content. 
  print('$ad failed to show: ${error.message}.');  
};  
_rewardedAd.onAdShowed = (AdScreenInstance ad) {  
  // Called when the ad showed the full screen content.
  print('$ad showed');  
};  
_rewardedAd.onAdImpression = (AdInstance ad, AdContentInfo contentInfo) { 
  // Called when an impression occurs on the ad. 
  print('$ad impression');  
};  
_rewardedAd.onAdClicked = (AdInstance ad) {  
  // Called when a click is recorded for an ad.
  print('$ad clicked');  
};  
_rewardedAd.onAdDismissed = (AdScreenInstance ad) { 
  // Called when the ad dismissed full screen content. 
  print('$ad dismissed');  
};
```

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](flutter/impression-level-data).
- When an error occurs during ad impression, executed the `onAdFailedToShow` only.  In this case the `onAdDismissed` will not be executed, since the impression is not considered successful.
</Info>

## Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.

```dart
_rewardedAd = CASRewarded.createAndLoad( 
  placement: "BestPlace", // [!code highlight]
)
```

## Show Ad
Be sure to implement `onUserEarnedReward` callback and reward the user for watching an ad.  
You can choose when to show the ad by calling `show()`:
```dart
_rewardedAd.onUserEarnedReward = (AdScreenInstance ad) {  
  print('Reward the user for watching the $ad');  
};
_rewardedAd.show();
```

The `onUserEarnedReward` callback differs from `onAdDismissed` because the user might not fulfill the requirements to receive the reward even after watching the ad.

If the ad is not ready at that moment, the `onAdFailedToShow` callback will be triggered with a reason provided in the `AdError`.

You have the option to check `isLoaded` if it's required by your app's logic.
```dart
bool isAdLoaded = await _rewardedAd.isLoaded();
```

## Release ad resource
Be sure to release ad resources if you’re no longer going to use the ad instance.
```dart
  @override
  void dispose() {
    _rewardedAd.dispose(); // [!code highlight]
    super.dispose();
  }
```
It may be useful to store the ad instance in static memory for reuse across multiple screens. This way, you don't need to call `dispose()` and can show the already loaded ad without delay.

## Manual reload Ad
When you want to manually control ad loading, use the `load()` function on the created ad instance to retry loading with the same configuration.
```dart
_rewardedAd.load();
```

## Extra fill by Interstitial Ad
CAS provides the option to load the interstitial ads as a fallback when a rewarded video ad has no available fill. Interstitial ads do not require the user to watch the entire ad to completion. However, the `onUserEarnedReward` will still be triggered as if the user completed the rewarded video.
```dart
_rewardedAd = CASRewarded.createAndLoad(
  extraFillByInterstitialAd: true, // [!code highlight]
  ...
)
```

## Mute Ad sounds
Indicates if the application’s audio is muted. Affects initial mute state for fullscreen ads. Use this method only if your application has its own volume controls (e.g., custom music or sound effect muting).
```dart
CASMobileAds.setAdSoundsMuted(true);
```
Not muted by default.

## Complete example
- [AppOpen ad example](https://github.com/cleveradssolutions/CAS-Flutter/blob/main/example/lib/main.dart#L189)
```

### Targeting options

Source: https://production.docs.page/docs/flutter/targeting-options

```mdx

You can now easily tailor the way you serve your ads to fit a specific audience!  
You’ll need to inform our servers of the users’ details so the SDK will know to serve ads according
to the segment the user belongs to.

### User ID
The userID is a unique identifier supplied by your application and must be static for each user across sessions. 
```dart
CASMobileAds.targetingOptions.setUserID("user-hash-code");
```

<Warning>  
Your userID should not contain any personally identifiable information such as  an email address, screen name, Android ID (AID), or Google Advertising ID (GAID).
</Warning>

### User Age
Set user age. Limitation: 1-99. By default 0 is 'unknown'.

 ```dart
CASMobileAds.targetingOptions.setAge(12);
```

### User Gender
Set targeting to user’s gender. Limitation: `unknown, male, female`.

 ```dart
CASMobileAds.targetingOptions.setGender(Gender.male);
```

### User Location
Set the user's current location. Location data is not used to CAS; however, it may be used by third party ad networks.

 ```dart
CASMobileAds.targetingOptions.setLocation(latitude: latitude, longitude: longitude);
```

<Warning>  
Do not use Location just for advertising. Your app should have a valid use case for it as well.
</Warning>

### User Location auto collection
Collect from the device the latitude and longitude coordinated truncated to the hundredths decimal place. 
- Collect only if your application already has the relevant end-user permissions.  
* Does not collect if the target audience is children.   
* Disabled by default.

 ```dart
CASMobileAds.targetingOptions.setLocationCollectionEnabled(true);
```

### App Keywords
Set a list of keywords, interests, or intents related to your application. Words or phrases describe
the current activity of the user for targeting purposes.

 ```dart
CASMobileAds.targetingOptions.setKeywords(keywords);
```

### App Content URL
Set the content URL for a website whose content matches the app's primary content. This website content is used for targeting and brand safety purposes. Limitation: max URL length 512.

 ```dart
CASMobileAds.targetingOptions.setContentUrl(contentUrl);
```
```

### User Consent Flow

Source: https://production.docs.page/docs/flutter/user-consent-flow

```mdx


<Info>
It is optional to use the CMP flow included with the CAS SDK. If you integrate your own CMP flow, make sure that flow completes before you initialize the CAS SDK.
</Info>

<Info>
If you implement a CMP that is compliant with IAB TCF v2 ([Transparency & Consent Framework](https://iabeurope.eu/tcf-2-0/)) for your user consent flow, the CAS SDK supports sending the TCF v2 consent to networks. In this case, the CAS Consent Flow will not be shown to the user.
</Info>

In order for CAS and our ad providers to deliver ads that are more relevant to your users, as a mobile app publisher, you need to collect explicit user consent for use of personal data in the regions covered by GDPR, CCPA, LGPD, PIPEDA.

### 1. Opt-in consent for the collection and use of personal data in the regions covered by GDPR, CCPA, LGPD, PIPEDA.
Any businesses established are required to comply with GDPR in Europe, CCPA in California, LGPD in Brazil, PIPEDA in Canada or risk facing heavy fines.

Keep in mind that it’s best to contact qualified legal professionals, if you haven’t done so already, to get more information and be well-prepared for compliance.  

Read more about:
- GDPR - [General Data Protection Regulation](https://gdpr-info.eu)
- CCPA - [The California Consumer Privacy Act](https://theccpa.org)
- LGPD - [General Personal Data Protection Act](https://lgpd-brazil.info)
- PIPEDA - [The Personal Information Protection and Electronic Documents Act](https://www.priv.gc.ca/en/privacy-topics/privacy-laws-in-canada/the-personal-information-protection-and-electronic-documents-act-pipeda/)

<Image height="400" alt="image" src="/assets/User-Consent-Flow-1.png" />


#### Users will not see the Consent dialog if at least one of following is true
- Users located in regions that are not covered by information protection
- Users who are subject to COPPA restrictions.

### 2. Asking user permission to track them or access their device’s advertising identifier
With iOS 14.5 and later, you need to receive the user’s permission through the `AppTrackingTransparency` framework in order to track them or access their device’s advertising identifier.  Read more about Asking Permission to Track and AppTrackingTransparency Framework on [Apple developer page](https://developer.apple.com/app-store/user-privacy-and-data-use/)

<Warning>  
If an app does not present this request, the IDFA will automatically be zeroed out, which may lead to a significant loss in ad revenue.
</Warning>

#### Users will not see the ATT request if at least one of the following is true
- Users using iOS versions below 14.5
- Users who have indicated that they do not allow apps to ask to track them, by setting *Settings > Privacy, Allow Apps to Request to Track*
- Users with child accounts, or who are under age 18, who are signed in via their Apple ID
- Users who have already answered so far
- The app does not have a usage tracking description in **Info.plist** under `NSUserTrackingUsageDescription` key

## Automatic consent flow
The automatic consent flow is enabled by default and described on the [CAS initialization page](flutter/initialize-cas).

## Manual consent flow
Call `showIfRequired()` on the `ConsentFlow` class. If the consent is required, the SDK loads a form and immediately presents it .
The `Future<int>` completes after the form is dismissed. If consent is not required, the `Future` completes immediately.

```dart
ConsentFlow.create().showIfRequired().then((int status){
  if (status == ConsentFlow.statusObtained) {
    // User consent obtained.
  }
});
```


| ConsentFlow constant   | Description                                                        |
| ---------------------- | ------------------------------------------------------------------ |
| statusObtained         | User consent obtained. Personalized vs non-personalized undefined. |
| statusNotRequired      | User consent not required.                                         |
| statusUnavailable      | User consent unavailable.                                          |
| statusInternalError    | There was an internal error.                                       |
| statusNetworkError     | There was an error loading data from the network.                  |
| statusFlowStillShowing | There was an error with another form is still being displayed.     |

<Warning>  
The cache consent status on your app or a previously saved consent string, could lead to a [TCF 3.3](https://support.google.com/admanager/answer/9999955) error if consent is expired.
</Warning>

## Privacy options button
Some consent forms require the user to modify their consent at any time. Adhere to the following steps to implement a privacy options button if required.

1. Implement a UI element, such as a button in your app's settings page, that can trigger a privacy options form.
2. Once `showIfRequired()` completes, check `isConsentObtained` to determine whether to display the UI element that can present the privacy options form.
3. When a user interacts with your UI element, call `show()` to show the form so the user can update their privacy options at any time.
```dart
bool _isConsentObtained = false;
  
void main() {  
  CASMobileAds.initialize(  
    casId: casId,  
  ).then((InitializationStatus status) {  
     _onConsentFlowDismissed(status.consentFlowStatus) // [!code highlight]
  }); 
  ...
} 

void _onConsentFlowDismissed(int status) {
  // The user completes the consent flow
  _isConsentObtained = status.consentFlowStatus == ConsentFlow.statusObtained;
}

void _showPrivacyOptionsForm() {
  ConsentFlow.create().show().then(_onConsentFlowDismissed);
}
```

## Debug geography
The SDK provides a way to test your app's behavior as though the device was located in the EEA or UK using the [PrivacyGeography](https://pub.dev/documentation/clever_ads_solutions/latest/clever_ads_solutions/PrivacyGeography.html) enum. 

Specify it in the SDK initialization arguments, and the setting will be applied only for test sessions.
```dart
CASMobileAds.initialize(  
  casId: casId,  
  forceTestAds: kDebugMode,
  debugPrivacyGeography: PrivacyGeography.europeanEconomicArea, // [!code highlight]
)
```

If you're showing the Consent Flow manually, define the `debugGeography` creation argument, and the setting will remain active even for production sessions. Leave it set to `.unknown` to allow the system to determine the user's geography automatically.
```dart
ConsentFlow.create(  
  debugGeography: kDebugMode // [!code highlight]
      ? PrivacyGeography.europeanEconomicArea // [!code highlight]
      : PrivacyGeography.unknown, // [!code highlight]
).showIfRequired();
```

## Meta Audience Network Data Processing Options for Users in California
The CAS does not support your handling of CCPA opt-out values for Meta Audience Network, you must work directly with the network to  purposes of your obligations for CCPA compliance.

To learn how to implement Meta Audience Network’s “Limited Data Use” flag, read the [Additional Meta AudienceNetwork steps](flutter/additional-meta-audiencenetwork-steps).
```

### Integrating with an AI agent

Source: https://production.docs.page/docs/general/ai-agent-integration

```mdx

You can hand a CAS.AI integration to an AI coding agent. This page is for both of you: it
tells you what to expect, and it tells the agent what it is not allowed to do.

## The documentation, for agents

The whole documentation is published in a form agents read directly, without rendering the
site:

| File | What it is |
| ---- | ---------- |
| [llms.txt](https://cleveradssolutions.docs.page/docs/llms.txt) | An index of every page with a one-line description. Small, fetch this first. |
| [llms-full.txt](https://cleveradssolutions.docs.page/docs/llms-full.txt) | The full text of every page in one file. Large, roughly a quarter of a million tokens. |

<Info>
Point your agent at `llms.txt` and let it fetch the pages it needs. Pasting
`llms-full.txt` into a prompt wastes context on eight platforms you are not using.
</Info>

## Agent skills

The documentation answers *where it is written*. A skill answers *in what order to do it,
what to ask you first, and what never to do*. We publish skills for Android and iOS in the
[documentation repository](https://github.com/cleveradssolutions/docs/tree/master/plugins).

<CodeGroup>
```bash Claude Code
/plugin marketplace add cleveradssolutions/docs
/plugin install cas-sdk@cas-skills
```

```bash Any agent
npx skills add cleveradssolutions/docs/plugins/cas-sdk/skills
```

```text By hand
Point the agent at the skill folder for your platform:

plugins/cas-sdk/skills/cas-android/SKILL.md
plugins/cas-sdk/skills/cas-ios/SKILL.md

Each folder is plain Markdown and is self contained.
```
</CodeGroup>

The first command uses the open [skills CLI](https://github.com/vercel-labs/skills), which
detects the agents installed on your machine and copies the skills into each one. It
supports Claude Code, Codex, Cursor, OpenCode and many others, and needs Node.js only to
run the installer. Add `--skill cas-android` for one platform, and update later with
`npx skills update`.

| Skill | What it does | Sample prompt |
| ----- | ------------ | ------------- |
| `cas-android` | Adds the SDK to a native Android app: Gradle setup, ad networks, initialization, consent, ad formats, verification on test ads. | *Add CAS.AI banner and interstitial ads to this app* |
| `cas-ios` | The same for a native iOS app, with Swift Package Manager or CocoaPods and the `Info.plist` configuration. | *Integrate CAS.AI into my iOS app and show a rewarded ad* |

<Info>
The skills are not Claude specific. `SKILL.md` is Markdown with a small header, and the
files it links to sit next to it. `AGENTS.md` in the repository root explains how to use
them from any other agent.
</Info>

Unity, the CAS Publishing Hub and the studio Firebase setup have their own agent guides in
the same repository, under `llm-guides/`. A Unity project belongs to those, not to the
Android and iOS skills.

<Info>
Because the agent clones the repository, it gets this documentation with the skill. A good
agent reads the page from its working copy instead of fetching the site, and quotes the
page rather than keeping its own copy of the integration code.
</Info>

## What the agent should ask you

A good integration starts with questions, not with code. Expect to be asked, and have the
answers ready:

- **Your CAS ID.** On Android it is normally the `applicationId`. On iOS it is the App
  Store id, the number from `apps.apple.com/.../id123456789`, not the bundle identifier.
- **Whether the app is registered** in the CAS dashboard.
- **New integration or a migration** from another mediation, and which one.
- **Which ad formats, and on which screens.**
- **Your audience:** child-directed, mixed, or adults only, and whether the app provides
  VPN or proxy services. This decides which solution is allowed.
- **Which solution:** Optimal, Families, VPN Compliant, or a hand-picked adapter list.
- **Consent:** our built-in flow, or a consent platform you already use.
- **iOS:** App Tracking Transparency, whether the app asks and with what text.
- **How it will be tested**, on which device and which build.

Anything the agent can read from your project, such as the minimum SDK version, the
dependency manager or the language, it should read rather than ask.

## Rules for the agent

These hold whichever agent you use, and whether or not it loaded our skill.

<Warning>
**Identifiers are never invented.** The CAS ID, the AdMob App ID and test device ids come
from the CAS dashboard or from you. An identifier copied from a sample app belongs to
someone else's account.
</Warning>

<Warning>
**CAS initializes the mediated ad networks.** The app must not call an ad network
initializer, and must not add network or adapter dependencies by hand. See
[Initialize CAS SDK](android/initialize-cas).
</Warning>

Also, in short:

- No ad request before initialization completes, and no analytics or attribution SDK
  started before the [consent flow](android/user-consent-flow) finishes.
- No `load()` call from inside a failure callback.
- Every ad instance is destroyed, on Android, or released, on iOS, with the screen that
  owns it.
- No personal data in targeting, and no location collection that exists only to serve ads.
- On iOS, the `Info.plist` ad network identifiers are written by our configuration script
  and re-run on every SDK update, never edited or trimmed by hand.
- No application id, bundle id, dependency version or deployment target changed silently
  to make a build pass.
- Store privacy disclosures, the ATT text and the decision about a child-directed audience
  are yours, not the agent's.

## Where ads belong

The agent should propose a placement and let you correct it, not place ads wherever the
code is easiest to change:

- **Interstitial:** loaded when the screen that shows it is created, shown on a transition
  the user is already making, such as a finished level or a closed screen. Never in the
  middle of a task.
- **Rewarded:** loaded early, shown only from a button the user pressed, with the reward
  stated before the press and granted on the reward callback, not when the ad is closed.
- **Banner:** in a fixed container at the top or the bottom, outside the scrolling content,
  never over a button, a navigation bar or game controls, with the height reserved so the
  layout does not jump.
- **App open:** only on a return to the app, or on a cold start while a loading screen is
  still up.
- **Native:** inside your own layout, marked as an ad, spaced so two are never on screen
  together.

<Warning>
An ad over a control earns accidental clicks, and accidental clicks are invalid traffic.
A misplaced ad costs more than no ad.
</Warning>

## What "done" means

Ask for evidence, not a summary. An integration is finished when the project builds, the
SDK initializes without an error, and a **test ad loads and is shown for every format that
was added**, with the log to prove it. A test full-screen ad also lists the mediation
adapters that initialized correctly, which is the fastest way to confirm the ad network
set is right.

<Warning>
Before you publish: test ad mode off, test device ids removed, debug logging off. See
[Enabling test ads](android/enabling-test-ads).
</Warning>
```

### Apple Ad Attribution

Source: https://production.docs.page/docs/general/apple-ad-attribution

```mdx

![AdNetworksID](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/cleveradssolutions/CAS-iOS/master/AdNetworkIdentifiers/AdNetworksShield.json)

To ensure proper ad attribution and maximize revenue performance, you must configure both **SKAdNetworkItems and AdAttributionKit** identifiers in your app’s `Info.plist`.

Proper configuration ensures that your app can attribute installs and in-app conversions correctly under Apple’s privacy framework:
* [x] Ensures full attribution coverage
* [x] Unlocks optimized campaign bidding
* [x] Improves fill rate and competition
* [x] Increases eCPM
* [x] Prevents revenue loss

<Warning>
**Missing identifiers cost you revenue, and nothing in the app tells you.** The app builds, ads still load, and no error appears, but you earn less for every impression.
</Warning>

Most iOS users don't allow tracking, so for them advertisers can measure their campaigns only through SKAdNetwork and AdAttributionKit. Apple sends an install postback only to ad networks whose identifier is in your `Info.plist`. When an identifier is missing:

* **The ad network can't attribute installs from your app.** An advertiser who can't see results from your inventory lowers the bid or stops buying it.
* **Fewer buyers compete for each impression.** The ad request tells buyers which identifiers your app declares, and many performance campaigns skip apps that don't declare theirs.
* **eCPM and fill rate drop**, most of all for users without the IDFA, who are usually the majority on iOS.
* **The loss is hard to notice.** Revenue shrinks gradually as new networks and identifiers appear, and your app doesn't have them.
* **Installs that already happened can't be attributed later.** Adding the identifiers in the next release doesn't recover the postbacks you lost.

Validate this configuration before every production release, and update the list whenever you update the SDK.

## SKAdNetwork
SKAdNetwork is Apple’s privacy-preserving attribution framework introduced in iOS 14 to replace traditional device-level attribution.

It allows ad networks to measure app installs and post-install events **without accessing user-level identifiers (IDFA)**.

[Official Apple documentation about SKAdNetwork](https://developer.apple.com/documentation/storekit/skadnetwork)

Each ad network participating in SKAdNetwork must register its unique SKAdNetwork ID.
To receive attribution postbacks, your app must include these IDs in Info.plist `SKAdNetworkItems` 

## AdAttributionKit
AdAttributionKit is Apple’s next-generation attribution framework introduced in iOS 17.4 that extends and evolves SKAdNetwork. It provides more advanced attribution capabilities and improved privacy-preserving reporting.

[Official Apple documentation about AdAttributionKit](https://developer.apple.com/documentation/adattributionkit)

AdAttributionKit identifiers must also be declared in your `Info.plist` to enable proper attribution for supported campaigns.

## Automated Integration
How the identifiers get into `Info.plist` depends on the platform you build with.

### Unity, Unreal, Cordova, React Native, Construct
The CAS.AI plugins for these platforms handle it for you. Each time the app is built, the plugin downloads the latest list of identifiers and updates `SKAdNetworkItems` and `AdNetworkIdentifiers` in `Info.plist`. You don't need to do anything else.

### iOS, Flutter, Kotlin Multiplatform
Run the [CAS.AI Ruby script](https://github.com/cleveradssolutions/CAS-iOS/tree/master/Script%20XCodeConfig) yourself to configure the Xcode project. It adds the required `SKAdNetworkItems` and `AdNetworkIdentifiers` identifiers to your `Info.plist`.

The steps for each platform are on its setup page: [iOS](ios#configure-infoplist), [Flutter](flutter), [Kotlin Multiplatform](kmp).

Run the script again before every release so that the list stays up to date.

## Manual Integration
An up-to-date list of SKAdNetworkItems and AdAttributionKit partners can be found in the repository.

1. Open your project in `Info.plist` as Source Code.
2. Copy the `<key>SKAdNetworkItems</key><array>...</array>` tags from the [SKAdNetworkItems.xml](https://github.com/cleveradssolutions/CAS-iOS/blob/master/AdNetworkIdentifiers/SKAdNetworkItems.xml).
3. Paste the content inside SKAdNetworkItems `<array>` tag or at the end of the file before `</dict></plist>`
4. Copy the `<key>AdNetworkIdentifiers</key><array>...</array>` tags from the [AdNetworkIdentifiers.xml](https://github.com/cleveradssolutions/CAS-iOS/blob/master/AdNetworkIdentifiers/AdNetworkIdentifiers.xml).
5. Paste the content inside AdNetworkIdentifiers `<array>` tag or at the end of the file before `</dict></plist>`

Additional `SKAdNetworkItems` and `AdNetworkIdentifiers` values may be added in the future. We recommend checking back on this page for updates.

## Best Practices
* Keep identifiers updated — Apple and ad networks may introduce new ones.
* Re-run the Ruby script when updating the SDK (iOS, Flutter, Kotlin Multiplatform).
* Validate configuration before App Store submission.
* Monitor attribution performance after release.
```

### Apple Kids Category

Source: https://production.docs.page/docs/general/apple-kids-category

```mdx

[The Kids category](https://developer.apple.com/app-store/kids-apps/) on the App Store is a great way for people to easily find apps specifically designed for children ages 11 and under on iPhone, iPod touch, and iPad.  
But the limits for advertising are too critical and only specialized ad networks for children, such as Kidoz and SuperAwesome, are allowed.  

CAS do not support a ready solution for Kids Category, but feel free to add Kidoz and SuperAwesome networks if you wish in `Advanced Integration` section.
```

### AppStore data disclosure

Source: https://production.docs.page/docs/general/appstore-data-disclosure

```mdx

Apple requires that developers publishing apps on the [App Store disclose certain information](https://developer.apple.com/app-store/app-privacy-details/) regarding their apps' data use. [Apple has announced](https://developer.apple.com/news/?id=vlj9jty9) that these disclosures will be required for new apps and app updates starting December 8, 2020.  

The following table specifies the data that is collected by the CAS mediation SDK, and can be used to correctly and accurately answer Apple’s privacy questionnaire.  

| **Contact info** | Collected? | Used for tracking? | Purpose |
|--------------|:----------:|:------------------:|---------|
| Name | No | - | - |
| Email Address | No | - | - |
| Phone Number | No | - | - |
| Physical Address | No | - | - |
| Other User Contact Info | No | - | - |
| **Health and Fitness** | **Collected?** | **Used for tracking?** | **Purpose** |
| Health | No | - | - |
| Fitness | No | - | - |
| **Financial Info** | **Collected?** | **Used for tracking?** | **Purpose** |
| Payment Info | No | - | - |
| Credit Info | No | - | - |
| Other Financial Info | No | - | - |
| **Location** | **Collected?** | **Used for tracking?** | **Purpose** |
| Precise Location | Yes | Yes | Third-party advertising |
| Coarse Location | Yes | Yes | Third-party advertising, Developer’s advertising or marketing, Analytics |
| **Sensitive Info** | **Collected?** | **Used for tracking?** | **Purpose** |
| Sensitive Info | No | - | - |
| **Contacts** | **Collected?** | **Used for tracking?** | **Purpose** |
| Contacts | No | - | - |
| **User Content** | **Collected?** | **Used for tracking?** | **Purpose** |
| Emails or Text Messages | No | - | - |
| Photos or Videos | No | - | - |
| Audio Data | No | - | - |
| Gameplay Content | No | - | - |
| Customer Support | No | - | - |
| Other User Content | No | - | - |
| **Browsing History** | **Collected?** | **Used for tracking?** | **Purpose** |
| Browsing History | No | - | - |
| **Search History** | **Collected?** | **Used for tracking?** | **Purpose** |
| Search History | No | - | - |
| **Identifiers** | **Collected?** | **Used for tracking?** | **Purpose** |
| User ID | Yes | Yes | Third-Party Advertising, Developer’s Advertising or Marketing |
| Device ID | Yes | Yes | Third-Party Advertising, Developer’s Advertising or Marketing |
| **Purchases** | **Collected?** | **Used for tracking?** | **Purpose** |
| Purchase History | Yes | Yes | Third-Party Advertising |
| **Usage Data** | **Collected?** | **Used for tracking?** | **Purpose** |
| Product Interaction | Yes | Yes | Third-Party Advertising, Developer’s Advertising or Marketing, Analytics |
| Advertising Data | Yes | Yes | Third-Party Advertising, Developer’s Advertising or Marketing, Analytics |
| Other Usage Data | No | - | - |
| **Diagnostics** | **Collected?** | **Used for tracking?** | **Purpose** |
| Crash Data | Yes | No | App functionality, Third-party advertising, Analytics |
| Performance Data | Yes | Yes | App functionality, Third-party advertising, Analytics |
| Other Diagnostic Data | Yes | Yes | Analytics |
| **Other Data** | **Collected?**  | **Used for tracking?** | **Purpose** |
| Other Data Types | Yes | Yes | Third-Party Advertising, Developer’s Advertising or Marketing, Analytics |
```

### App-ads.txt

Source: https://production.docs.page/docs/general/authorized-sellers-for-apps

```mdx

[app-ads.txt](https://iabtechlab.com/wp-content/uploads/2019/03/app-ads.txt-v1.0-final-.pdf) is a vital text file that app developers upload to their websites, listing the ad sources authorized to sell their inventory. Similar to the web, the IAB has established a system that enables buyers to verify who is permitted to buy and sell specific in-app ad inventory. This initiative plays a crucial role in combating fraud and enhancing transparency and efficiency across the ecosystem. Consequently, most savvy brand marketers and demand-side platforms (DSPs) tend to avoid purchasing inventory without app-ads.txt implementation.

## How app-ads.txt Works for Mobile Apps

When a DSP seeks to bid on app inventory, it follows a chain of checks:

1. The app's store listing points to the **developer website**.
2. The DSP reads `app-ads.txt` from the root of that website.
3. The file contains the CAS.AI seller line for your account: `cas.ai, <your seller ID>, DIRECT`.
4. The same seller ID is listed in [cas.ai/sellers.json](https://cas.ai/sellers.json).

The DSP will only accept bid requests from the ad sources listed in this file. If any link of the chain is broken, your impressions are bought at a lower price or not bought at all.

## Benefits of Implementing app-ads.txt for Your Mobile App

1. **Attract Brand Budgets**  
   Major brands and agencies are more inclined to purchase app inventory through DSPs that verify authorized ad sources. By implementing app-ads.txt, developers signal to DSPs that their inventory is secure. Those who neglect to adopt app-ads.txt risk exclusion from DSPs' targeted media pools.

2. **Combat Ad Fraud**  
   Malicious actors may create counterfeit apps that impersonate legitimate ones, misleading DSPs into spending brand budgets on fraudulent inventory. This not only harms legitimate developers but also deprives them of revenue intended for their apps. Implementing app-ads.txt helps prevent unauthorized impersonation and minimizes instances of fraud, ultimately safeguarding developers’ financial interests.

<Warning>
Failing to implement app-ads.txt could negatively impact your eCPMs, as fewer advertisers may be willing to engage with your app.  
If you manage multiple domains, ensure that all relevant domains are updated accordingly.
</Warning>

## Get your app-ads.txt file

Each developer account has its own app-ads.txt file in the [CAS.AI dashboard](https://platform.cas.ai). The file is built from three parts:
- The entries of all CAS.AI mediation partners, maintained by the CAS.AI team.
- Your personal seller line `cas.ai, <your seller ID>, DIRECT`, linked to your record in sellers.json.
- Additional lines for your account, if your account manager added any.

To find the file:

<Steps>
<Step title="Open Applications">
Open **Applications** in the [CAS.AI dashboard](https://platform.cas.ai).
</Step>
<Step title="Open the app-ads.txt window">
Click the status in the **APP-ADS** column of your app.
</Step>
<Step title="Get the file">
In the app-ads.txt window, open the **Full file** tab and click **Download app-ads.txt** or **Copy**.  
On the **Missing** tab the same buttons take only the lines your published file lacks.
</Step>
</Steps>

<Image zoom width="750" alt="The app-ads.txt window in the CAS.AI dashboard" src="/assets/App-ads-txt.png" />

<Info>
A developer is a store account (Google Play, App Store), not a company. If you publish in both stores, you have two developer accounts, two files and two developer pages.  
If the listings of both accounts point to the same website, its app-ads.txt must hold the seller lines of both accounts.
</Info>

## Choose your developer website

The **Developer Website** in your store listing tells ad networks where to look for app-ads.txt. You have two options.

<Tabs>
<TabItem label="Your own website" value="own">

<Steps>
<Step title="Download the file">
Download your app-ads.txt from the dashboard.
</Step>
<Step title="Upload it to your website">
Place it at the root of your website: `https://example.com/app-ads.txt`.  
If you already have an app-ads.txt with other ad sources, add the CAS.AI lines to it and keep the rest.
</Step>
<Step title="Set it in the store listing">
Set your website as the **Developer Website** of every app in the store listing.
</Step>
</Steps>

<Warning>
You are responsible for keeping the file up to date. When CAS.AI adds partners or changes lines, the app status changes to **Missing** until you update the file on your website. Check the dashboard regularly.
</Warning>

</TabItem>
<TabItem label="CAS.AI developer page" value="landing">

CAS.AI creates a developer page for you on your own subdomain, like `vXXXXXXXX.cas-apps.com`. The page already serves your app-ads.txt and redirects visitors to your developer page in the store.

<Steps>
<Step title="Copy the developer page">
In the app-ads.txt window, click **Copy developer page**.  
If the button is locked, ask your account manager for a developer page.
</Step>
<Step title="Set it in the store listing">
Set the copied address as the **Developer Website** of every app in the store listing, as described [below](#updating-a-developer-website).
</Step>
</Steps>

That is all. The file on the developer page is always up to date: CAS.AI updates it every time the list of partners changes.

</TabItem>
</Tabs>

<Warning>
Do not set a CAS.AI website (`cas.ai`, `psvgamestudio.com`, `cleveradssolutions.com` or another CAS.AI domain) as your Developer Website. The check reports it as **Old domain**, and your account is not listed in sellers.json until one of your apps points to a website of your own or to your developer page.
</Warning>

## Check the status in the dashboard

CAS.AI checks app-ads.txt of every app once a day, at 08:00 UTC. It finds your app in the store, reads the Developer Website from the store listing and compares the app-ads.txt on that website with your file in the dashboard. If your own website is in the store listing, the file on your website is checked, not the one on the developer page.

The result is shown in the **APP-ADS** column of **Applications**. To show every app with a problem at once, choose **All issues** in the app-ads filter.

| Status | Meaning | What to do |
|---|---|---|
| **OK** | The file is found and has all required lines. | Nothing. |
| **Not checked** | The app has not been checked yet. | Wait for the next daily check. |
| **Missing** | The file is found, but some lines are missing. The app-ads.txt window lists them. | Add the missing lines to the file on your website, or switch to the CAS.AI developer page, where the file is always complete. |
| **Issue** | The store listing has no Developer Website, or the website does not return the file: it cannot be reached, does not answer in time, answers with an HTTP error or a web page, or the file is larger than 10 MB. The app-ads.txt window names the reason. | Set the Developer Website in the store listing. If it is set, make sure `https://<your website>/app-ads.txt` opens in a browser as plain text. |
| **Old domain** | The store listing points to a CAS.AI website that is no longer used for app-ads.txt. | Replace the Developer Website with your CAS.AI developer page: click **Copy developer page** in the app-ads.txt window. |
| **No store** | The app is not found in the store. | When the app is back in the store, click **Check again** in the app-ads.txt window. |

After fixing the problem, click **Check again** in the app-ads.txt window to check the app without waiting for the daily check. You can do it up to 10 times a minute.

<Info>
After you change the Developer Website, the store needs time to update the listing, and the status does not change until it does. If the app-ads.txt window says the store listing has not changed yet, check again in a few hours. Ad networks also need time to crawl the new file: AdMob, for example, may take up to 24 hours.
</Info>

### Notifications

When an app gets the status **Missing**, **Issue** or **Old domain**, the **Applications** page shows the **App-ads.txt issue detected** banner, and CAS.AI emails you the list of affected apps. The banner disappears once every app is fixed.

## Updating a Developer Website
It is important to pay attention to the instructions below before beginning the app-ads.txt implementation.
- You must list your **Developer Website URL** in the App Store and Google Play, as relevant.
- There must be a valid developer website URL in all app stores hosting your apps.
- This app-ads.txt guide only addresses Apple's App Store and Google Play stores, with both you can fully comply with the specs of app-ads.txt.
- The Developer Website URL is used by advertising platforms to locate the app-ads.txt file. Only the host name is used: you don't need to put the full file URL in the store listing.

<Tabs>
<TabItem label="AppStore" value="appstore">
  
Developer page is listed under **Developer Website**:  
![image](https://user-images.githubusercontent.com/22005013/114005460-3b122e00-9868-11eb-92bb-e8dce76b1b12.png)  

Follow these instructions to either update or add a developer website to the App Store page:
<Steps>
<Step title="Open App Store Connect">
On the Apple Developer Program page, click **App Store Connect**.
</Step>
<Step title="Select the app">
Select the app for which you want to add a new version.
</Step>
<Step title="Add a new version">
Inside the app, click **+** for **Version or Platform**.
</Step>
<Step title="Set the Marketing URL">
In the new version add the **Marketing URL**.
</Step>
</Steps>

</TabItem>
<TabItem label="GooglePlay" value="googleplay">
  
The developer page is listed under **Visit Website**:  
![image](https://user-images.githubusercontent.com/22005013/114006234-f1761300-9868-11eb-952f-176b1937308a.png)  

Follow these instructions to either update or add a developer website to Google Play:
<Steps>
<Step title="Select the app">
On the **Google Play Console** select the game for which you want to add a website.
</Step>
<Step title="Open the store listing">
On the left menu bar click **Store Presence >> Store Listing**.
</Step>
<Step title="Enter the app details">
Enter the details of your app.
</Step>
<Step title="Set the website">
Enter your contact details including the **Website**.
</Step>
</Steps>

</TabItem>
</Tabs>

## Ensure your app-ads.txt files can be crawled
If you host the file on your own website, work through the following troubleshooting steps. The CAS.AI developer page already meets all of them.

### How CAS.AI reads the file
CAS.AI reads `https://<root domain>/app-ads.txt`, where the root domain is the host of your Developer Website with a leading `www.` or `m.` removed. It falls back to `http://` only when `https://` cannot connect, and follows up to 5 redirects. The response must be the plain-text file itself: a web page returned for that address counts as **Issue**.

<Info>
The following information was taken from a [Google Support resource](https://support.google.com/admob/answer/9679128).
</Info>

### Confirm that the file is reachable from the root domain
Redirects from `domain.com/app-ads.txt` to `www.domain.com/app-ads.txt` are fairly common. App-ads.txt crawling will start at the root domain. The root domain needs to return from, or redirect to, the app-ads.txt file.  

<Warning>
An app-ads.txt file on `www.domain.com/app-ads.txt` will only be crawled if `domain.com/app-ads.txt` redirects to it.
</Warning>

### Confirm the file is not temporarily unavailable
If a previously seen app-ads.txt file is unavailable on a subsequent re-crawl, the previously seen entries will be:
- Purged if the response is a hard 404 error (page that actually doesn’t exist; HTTP 404 status).
- Retained for up to five days if the response is a soft 404 error (a real page returned for a URL that doesn't actually exist; HTTP 200 status) or a 500 server error.

### Ensure file is returned with an HTTP 200 OK status code
While a request for an app-ads.txt file may return the contents of the file in the response body, if the status code in the response header indicates the file was not found (e.g., status code 404):
- The response will be ignored.
- The file will be considered non-existent.  

Make sure the file has an HTTP 200 OK status code.

### Ensure there are no formatting errors or invalid characters in the file
Formatting errors, such as invalid whitespace characters, may be difficult to detect but can make an app-ads.txt file difficult to parse by a crawler, and may therefore result in a file being ignored. Avoid copying and pasting app-ads.txt entries from a rich text editor; we recommend a plain text editor. You can also check for invalid UTF-8 characters in your app-ads.txt file using a HEX editor. 

Each line has the format defined by the IAB:
```
<ad source domain>, <publisher account ID>, <DIRECT or RESELLER>[, <certification authority ID>]
```
Everything after `#` is a comment. To check the upload, open `https://<your website>/app-ads.txt` in a browser: if the content is displayed, crawlers will most likely find it too.
```

### Google Play data disclosure

Source: https://production.docs.page/docs/general/google-play-data-disclosure

```mdx

This page can help you complete the requirements for this data disclosure in regards to your usage of the CAS.AI Mediation SDKs. We aim to be as transparent as possible in supporting you; however, as the app developer, you are solely responsible for deciding how to respond to Google Play's Data safety section form regarding your app's end-user data collection, sharing, and security practices.

To complete your data disclosure, you can use Android's [guide about data types](https://developer.android.com/guide/topics/data/collect-share) to help you determine which [data types](https://support.google.com/googleplay/android-developer/answer/10787469#in_play_console&zippy=%2Cdata-types) and purposes best describe the collected data. In your data disclosure, make sure to also account for how your specific app shares and uses the collected data.

CAS Mediation integrates third-party ad networks that may collect and process user data independently. Review the privacy policies and data practices of each ad network you enable in your mediation stack.

## Families Ads Solution
Apps designed for children have special restrictions on data usage for advertising. Our Families Ads Solution includes only those ad SDKs that can operate without collecting any user data. Therefore, you only need to answer the first question:
- Does your app collect or share any of the required user data types?
- No

## Optimal Ads Solution
To help simplify the process, we’ve prepared a configuration CSV file that you can download and import directly into your app’s Data safety section in the Play Console.
- Download the [Data safety CSV file](https://github.com/cleveradssolutions/CAS-Android/releases/download/4.1.0/data_safety_export.csv)

The provided CSV file includes the default disclosures for the **Optimal Ads Solutions**. You may need to modify or extend it depending on your integration, app features, or additional partners you work with. 

Even though CAS provides guidance for SDK-level data usage, your app may collect additional data through other means. Ensure that your disclosure reflects your complete data practices.

Where appropriate, update your app’s privacy policy and in-app consent flows to reflect SDK usage and user data handling, especially if targeting users in jurisdictions with specific data protection laws (e.g., GDPR, CCPA).
```

### CAS.AI Reporting API

Source: https://production.docs.page/docs/general/reportingapi

```mdx

The CAS.AI API is built on HTTP and JSON, so any standard HTTP client can send requests to it and parse the responses.

## Authorization
Every request your application sends to the CAS.AI API must include an authorization token. 
```
https://b2b.cas.ai/api/login
```

### POST Request: multipart/form-data
```json
{ "email": "examapl@host.com", "password": "account password" }
```

### Response: JSON
```json
{ "access_token": "Authorization token" }
```

Use token for Authorization every API request using the Bearer scheme. For example in request header:
```
Authorization: Bearer <access_token>
```
<Info>
Token lifetime: 15 minutes.
</Info>

## Mediation report
```
https://b2b.cas.ai/api/mediation/data
```

### POST Request body: application/json
Request object structure:

| Field     | Type             | Description                                                                 |
| --------- | ---------------- | --------------------------------------------------------------------------- |
| filter    | array of objects | Mandatory filter options for report. See [table of filter](general/reportingapi#filters) below. |
| columns   | array of objects | List of columns for report. See [table of columns](general/reportingapi#columns) below.         |
| calcTotal | boolean          | Append total row for report. (`true` or `false`)                            |
| currency  | string           | Currency of revenue, `euro` or `usd` supported only.                        |

#### Filters
The filter options have the following structure:
```json
"filter": [
    { "type": "app", "value": 1 },
    { "type": "app", "value": 2 }
]
```

| Filter type | Description                                                                                                  | Value Example                                                     |
| ----------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- |
| `date`      | (Required) The first and last days you want in the report, in `«YYYY»-«MM»-«DD»` format.                     | `"value": { "beginDate": "YYYY-MM-DD", "endDate": "YYYY-MM-DD" }` |
| `app`       | Report for selected application(s) id. Use id from [Applications Ids list](general/reportingapi#applications-ids-list) response. | `"value": 1`                                                      |
| `country`   | Report for selected country(s) id. Use id from [Countries Ids list](general/reportingapi#countries-ids-list) response.           | `"value": 4`                                                      |
| `format`    | Report for selected format(s) id. See [table of ad format ids](general/reportingapi#ad-format-ids) below.                        | `"value": 2`                                                      |
| `ad_source` | Report for selected ad source(s) id. Use id from [Ad Sources Ids list](general/reportingapi#ad-sources-Ids-list) response.       | `"value": 3`                                                      |

<Warning>
You must add `date` filter for each report request.
</Warning>

#### Columns
The filter options have the following structure:
```json
"columns": [
    { "id": "app" },
    { "type": "date" }
]
```

| Column id                   | Description                                                                                  |
| --------------------------- | -------------------------------------------------------------------------------------------- |
| `ad_source`                 | Ad source id column. Use id from [Ad Sources Ids list](general/reportingapi#ad-sources-Ids-list) response.       |
| `app`                       | Application id column. Use id from [Applications Ids list](general/reportingapi#applications-ids-list) response. |
| `date` or `week` or `month` | Date, Week or Month column                                                                   |
| `country`                   | Country id column. Use id from [Countries Ids list](general/reportingapi#countries-ids-list) response.           |
| `format`                    | Ad Format id column. See [table of ad format ids](general/reportingapi#ad-format-ids) below.                     |
| `platform`                  | Application name platform column                                                             |
| `impressions`               | Number of impressions shown                                                                  |
| `observed_ecpm`             | Observed ECPM column                                                                         |
| `est_earnings`              | Estimated earnings column                                                                    |
| `dau`                       | DAU column. Available only if `ad_source` and `format` columns not requested.                |
| `arpu`                      | ARPU column. Available only if `ad_source` and `format` columns not requested.               |

## Ad Format ids

| Id  | Name            |
| --- | --------------- |
| 1   | Banner Ad       |
| 2   | Interstitial Ad |
| 3   | Rewarded Ad     |
| 4   | Native Ad       |
| 5   | AppOpen Ad      |
| 6   | In Game Ad      |

## Ad Sources Ids list
```
https://b2b.cas.ai/api/mediation/adsources
```

### GET Request: 
NO Parameters  
### Response: JSON
```json
[
    {
        "Id ": 2,
        "AdSource_Name": "AdMob"
    },
    {
        "Id ": 3,
        "AdSource_Name": "Mintegral"
    }
]
```

Array of objects with structure

| Field         | Type    | Description           |
| ------------- | ------- | --------------------- |
| Id            | integer | Ad source database id |
| AdSource_Name | string  | Name of the Ad Source |

## Countries Ids list
```
https://b2b.cas.ai/api/mediation/country
```

### GET Request: 
NO Parameters  
### Response: JSON

```json
[
    {
        "Id": 4,
        "Country_Name": "Azerbaijan"
    },
    {
        "Id": 5,
        "Country_Name": "Bangladesh"
    },
    {
        "Id": 6,
        "Country_Name": "Belgium"
    }
]
```

Array of objects with structure

| Field        | Type    | Description         |
| ------------ | ------- | ------------------- |
| Id           | integer | Country database id |
| Country_Name | string  | Name of the Country |

## Applications Ids list
```
https://b2b.cas.ai/api/mediation/apps
```

### GET Request: 
NO Parameters  
### Response: JSON
```json
[
    {
        "App_ID": 998,
        "Bundle_ID": "com.psv.ladybug.color_by_number",
        "Name": "Miraculous Ladybug: Coloring",
        "Status": "active"
    },
    {
        "App_ID": 999,
        "Bundle_ID": "com.hyppo.goodnight",
        "Name": "Good Night Hippo",
        "Status": "active"
    }
]
```

Array of objects with structure

| Field     | Type    | Description                              |
| --------- | ------- | ---------------------------------------- |
| App_ID    | integer | Database id                              |
| Bundle_ID | string  | Android bundle name or iTunes Id         |
| Name      | string  | Name of the application.                 |
| Status    | string  | Status: `active` or `test` or `inactive` |

## Mediation report POST Request example
```json
{
    "filter": [
        {
            "type": "date",
            "value": {
                "beginDate": "2021-12-09",
                "endDate": "2021-12-15"
            }
        },
        { "type": "app", "value": 1 },
        { "type": "country", "value": 4 }
    ],
    "columns": [
        { "id": "ad_source" },
        { "id": "week" },
        { "id": "format" },
        { "id": "impressions" },
        { "id": "observed_ecpm" },
        { "id": "est_earnings" }
    ],
    "calcTotal": true
}
```

## Mediation report response example
```json
{
    "list": [
        {
            "impressions": "219",
            "observed_ecpm": 0.5342465693547845,
            "est_earnings": 0.11699999868869781,
            "week": "2021-0",
            "ad_source": 2,
            "format": 2
        },
        {
            "impressions": "141",
            "observed_ecpm": 0.19148935345893212,
            "est_earnings": 0.026999998837709427,
            "week": "2021-0",
            "ad_source": 2,
            "format": 3
        }
    ],
    "totals": {
        "impressions": "6820",
        "observed_ecpm": 0.31428592090250496,
        "est_earnings": 2.1434299805550836
    }
}
````
```

### Ad errors

Source: https://production.docs.page/docs/ios/ad-errors

```mdx

In cases where an ad fails to load/show, a callback is called which provides a `AdError` object.

AdError is commonly used in ad-related callbacks such as `didFailToLoadWithError` or `didFailToPresentWithError`.
 
This ad error object has the following methods:
- `code: AdErrorCode`  
    Returns the unique `AdErrorCode` that identifies the type of error. 
    Use to programmatically handle specific error cases.
- `description: String`  or  `localizedDescription` same
    Returns a human-readable message describing the error.  
    Use for for logging or debugging purposes.

### AdErrorCode constants
All errors are divided into the following categories defined in `AdErrorCode`.

| Code | Constant           | Description                                                                                                                                                                                            |
| ---- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 0    | internalError      | Indicates an internal error occurred.                                                                                                                                                                  |
| 1    | notReady           | Indicates that ads are not ready to be shown. Ensure to call the appropriate ad loading method or use automatic load mode. If using automatic load mode, wait a little longer for ads to be ready.     |
| 2    | rejected           | Indicates that the device is rejected for services. Services may not be available for some devices that do not meet the requirements. For example, the country or version of the OS.                   |
| 3    | noFill             | Indicates that no ads are available to be served. If ads are visible in test ads mode, your implementation is correct, and ads will be served once live.                                               |
| 6    | reachedCap         | Indicates that the ad creative has reached its daily cap for the user. This is typically relevant for cross-promotion ads only.                                                                        |
| 7    | notInitialized     | Indicates that the CAS Mediation is not initialized. Ensure to add SDK initialization code in your App delegate.                                                                                       |
| 8    | timeout            | Indicates a timeout error occurred because the advertising source did not respond in time. The system will continue waiting for a response, which may delay ad loading or cause a loading error.       |
| 9    | noConnection       | Indicates that there is no internet connection available, which prevents ads from loading.                                                                                                             |
| 10   | configurationError | Indicates that there is a configuration error in one of the mediation ad sources. Report this error to your support manager for further assistance.                                                    |
| 11   | notPassedInterval  | Indicates that the interval between impressions of interstitial ads has not yet passed. This error may also occur if a trial ad-free interval has been defined and has not yet passed since app start. |
| 12   | alreadyDisplayed   | Indicates that another fullscreen ad is currently being displayed, preventing new ads from showing. Review your ad display logic to avoid duplicate impressions.                                       |
| 13   | notForeground      | Indicates that ads cannot be shown because the application is not currently in the foreground.                                                                                                         |
```

### Additional Meta AudienceNetwork steps

Source: https://production.docs.page/docs/ios/additional-meta-audiencenetwork-steps

```mdx


## iOS Advertising Tracking Enabled for Audience Network
Implement the [setAdvertiserTrackingEnabled](https://developers.facebook.com/docs/audience-network/setting-up/platform-setup/ios/advertising-tracking-enabled) flag, irrespective of the use of mediation, to inform Facebook whether to use the data to deliver personalized ads.  
Set flag to inform Audience Network to use the data to deliver personalized ads in line with your own legal obligations, platform terms, and commitments you’ve made to your users.

<CodeGroup synchronize="true">
```swift
import CleverAdsSolutions
import FBAudienceNetwork

func requestATT() {
    FBAdSettings.setAdvertiserTrackingEnabled(enabled)
    CAS.create(...)
}
```

```objc
#import <CleverAdsSolutions/CleverAdsSolutions.h>
#import <FBAudienceNetwork/FBAdSettings.h>

- (void)requestATT {
    [FBAdSettings setAdvertiserTrackingEnabled:enabled];
    [CAS create :...];
}
```
</CodeGroup>

## Data Processing Options for US Users
Meta Audience Network Data Processing Options for US Users Limited Data Use is a data processing option that gives you more control over how your data is used in Meta’s systems and better supports your compliance efforts with various US state privacy regulations. To utilize this feature, you must proactively enable Limited Data Use.  
Visit [Meta’s developer documentation](https://developers.facebook.com/docs/marketing-apis/data-processing-options) for details.

If you do not want to enable Limited Data Use (LDU) mode, pass an empty string array:

<CodeGroup synchronize="true">
```swift
FBAdSettings.setDataProcessingOptions([])
```

```objc
[FBAdSettings setDataProcessingOptions:@[]];
```
</CodeGroup>


To enable LDU for users and specify user geography, call `setDataProcessingOptions` in a form like this:

<CodeGroup synchronize="true">
```swift
FBAdSettings.setDataProcessingOptions(["LDU"])
```

```objc
[FBAdSettings setDataProcessingOptions:@[@"LDU"]];
```
</CodeGroup>

You can determine whether the user has consented to Meta or not with Additional Consent from CMP. To do so, use code like the following:

<CodeGroup synchronize="true">
```swift
let metaConsent = CAS.settings.getAdditionalConsent(providerId: 89);
if (metaConsent == CASConsentStatus.accepted) {
    FBAdSettings.setDataProcessingOptions([])
} else if (metaConsent == CASConsentStatus.denied) {
    FBAdSettings.setDataProcessingOptions(["LDU"])
} else {
    // AC String is not available on disk. 
    // Please check for consent status after the user completes the CMP flow.
}
```

```objc
CASConsentStatus metaConsent = [CAS.settings getAdditionalConsentWithProviderId:89];

if (metaConsent == CASConsentStatusAccepted) {
    [FBAdSettings setDataProcessingOptions:@[]];
} else if (metaConsent == CASConsentStatusDenied) {
    [FBAdSettings setDataProcessingOptions:@[@"LDU"]];
} else {
    // AC String is not available on disk.
    // Please check for consent status after the user completes the CMP flow.
}
```
</CodeGroup>
```

### App Open Ads

Source: https://production.docs.page/docs/ios/app-open-ads

```mdx

App open ads are a special ad format intended for publishers wishing to monetize their app load screens.
App open ads can be closed at any time, and are designed to be shown when your users bring your app to the foreground.  
App open ads automatically show a small branding area so users know they're in your app.  

Below is a diagram showing the ad lifecycle.
<Image zoom src="/assets/ios/Lifecycle-Screen-Ad.png" alt="Diagram" height="500" />


## Create Ad instance

<CodeGroup synchronize="true">
```swift
import CleverAdsSolutions

@main
class MyAppDelegate: UIResponder, UIApplicationDelegate, CASScreenContentDelegate {

    let appOpenAd = CASAppOpen(casID: MyAppDelegate.casID)

```

```objc
#import <CleverAdsSolutions/CleverAdsSolutions.h>

@interface MyAppDelegate : UIResponder <UIApplicationDelegate, CASScreenContentDelegate>
@property (nonatomic, strong) CASAppOpen *appOpenAd;
@end

@implementation MyAppDelegate

- (instancetype)init {
    self = [super init];
    if (self) {
        _appOpenAd = [[CASAppOpen alloc] initWithCasID:MyAppDelegate.casID];
    }
    return self;
}

// ...
@end
```
</CodeGroup>

The SDK provides the capability to create and precache multiple ad instances, enabling uninterrupted sequential ad display. CAS SDK will load mediation ads in order for each created instance.

## Receive Ad events
The `CASScreenContentDelegate` handles events related to displaying your `CASAppOpen`. Callbacks are called on the main thread. Before showing ad, make sure to set `delegate`.

<CodeGroup synchronize="true">
```swift
func screenAdDidLoadContent(_ ad: any CASScreenContent) {
    // Called when the ad content has been successfully loaded.
}

func screenAd(_ ad: any CASScreenContent, didFailToLoadWithError error: AdError) {
    // Called when the ad content fails to load.
}

func screenAd(_ ad: any CASScreenContent, didFailToPresentWithError error: AdError) {
    // Called when the ad content fails to present.
}

func screenAdWillPresentContent(_ ad: any CASScreenContent) {
    // Called when the ad content is successfully shown.
}

func screenAdDidClickContent(_ ad: any CASScreenContent) {
    // Called when the ad content is clicked by the user.
}

func screenAdDidDismissContent(_ ad: any CASScreenContent) {
    // Called when the ad content is dismissed.
}
```

```objc
- (void)screenAdDidLoadContent:(id<CASScreenContent>)ad {
    // Called when the ad content has been successfully loaded.
}

- (void)screenAd:(id<CASScreenContent>)ad didFailToLoadWithError:(CASError * _Nonnull)error {
    // Called when the ad content fails to load.
}

- (void)screenAd:(id<CASScreenContent>)ad didFailToPresentWithError:(CASError *)error {
    // Called when the ad content fails to present.
}

- (void)screenAdWillPresentContent:(id<CASScreenContent>)ad {
    // Called when the ad content is successfully shown.
}

- (void)screenAdDidClickContent:(id<CASScreenContent>)ad {
    // Called when the ad content is clicked by the user.
}

- (void)screenAdDidDismissContent:(id<CASScreenContent>)ad {
    // Called when the ad content is dismissed.
}
```
</CodeGroup>

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](ios/impression-level-data).
- Attempting to load a new ad from the `didFailToLoadWithError` method is strongly discouraged. Limit ad load retries to avoid continuous failed ad requests in situations such as limited network connectivity.
- When an error occurs during ad impression, executed the `didFailToPresentWithError` only.  In this case the `didDismissContent` will not be executed, since the impression is not considered successful.
</Info>

## Load Ad
The next step is to fill out the `loadAd()` method and handle the ad load callbacks.

<CodeGroup synchronize="true">
```swift
func loadAppOpenAd() {
    let screenContentDelegate: CASScreenContentDelegate = self
    appOpenAd.delegate = screenContentDelegate
    appOpenAd.loadAd()
}
```

```objc
- (void)loadAppOpenAd {
    id<CASScreenContentDelegate> screenContentDelegate = self;
    self.appOpenAd.delegate = screenContentDelegate;
    [self.appOpenAd loadAd];
}
```
</CodeGroup>


### Autoload mode
If enabled, the ad will automatically load new content when the current ad is dismissed or completed. Additionally, it will automatically retry loading the ad if an error occurs during the loading process.  

<CodeGroup synchronize="true">
```swift
func loadAppOpenAd() {
    let screenContentDelegate: CASScreenContentDelegate = self
    appOpenAd.delegate = screenContentDelegate
    appOpenAd.isAutoloadEnabled = true
}
```

```objc
- (void)loadAppOpenAd {
    id<CASScreenContentDelegate> screenContentDelegate = self;
    self.appOpenAd.delegate = screenContentDelegate;
    self.appOpenAd.isAutoloadEnabled = YES;
}
```
</CodeGroup>

By default autoload disabled.

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements.

The placement name should be set before showing the ads. Maximum 100 characters allowed for the placement name.

<CodeGroup synchronize="true">
```swift
appOpenAd.placement = "BestPlace"
```

```objc
appOpenAd.placement = @"BestPlace";
```
</CodeGroup>

## Show Ad
The most common app open implementation is to attempt to present an app open ad near app launch, start app content if the ad isn't ready, and preload another ad for the next app open opportunity.

<CodeGroup synchronize="true">
```swift
func applicationDidBecomeActive(_ application: UIApplication) { 
    if appOpenAd.isLoaded {  
        appOpenAd.present(from: nil);  
    } else {  
        loadAppOpenAd();  
    } 
}
```

```objc
- (void)applicationDidBecomeActive:(UIApplication *)application {
    if (self.appOpenAd.isAdLoaded) {
        [self.appOpenAd presentFromViewController: nil];
    } else {
        [self loadAppOpenAd];
    }
}
```
</CodeGroup>

Starting with CAS SDK version 4.3.0, all ads functions can be safely called from any thread.

If you use [Scenes](https://developer.apple.com/documentation/uikit/app_and_environment/scenes), implement the [`sceneDidBecomeActive:`](https://developer.apple.com/documentation/uikit/uiscenedelegate/3197915-scenedidbecomeactive) method in your `UISceneDelegate` instead.

The `UIViewController` parameter is an optional. The SDK uses the app’s main window to look up view controllers automatically when one is not provided.

Once you’ve successfully call `preset(from:)`, you will have shown your user an App Open Ad.  
In the case you want to serve another App Open Ad, you must repeat `loadAd()` to request an additional ad.

<Info>
If a user returns to your app after having left it by clicking on an app open ad, it makes sure they're not presented with another app open ad.
</Info>

### Autoshow mode
Use the `isAutoshowEnabled` property to automatically show a loaded ad when the user returns to the app.

<CodeGroup synchronize="true">
```swift
appOpenAd.isAutoshowEnabled = true
```

```objc
appOpenAd.isAutoshowEnabled = YES;
```
</CodeGroup>

By default autoshow disabled.

### Checking Ad Availability
Use `isAdLoaded` to check whether an ad is currently loaded.

<CodeGroup synchronize="true">
```swift
if appOpenAd.isAdLoaded {
    // ...
}

```
```objc
if (appOpenAd.isAdLoaded) {
    // ...
}
```
</CodeGroup>

Even if `isAdLoaded` returns `true`, it does not guarantee that the ad will be shown successfully — various issues may still prevent it from being displayed. We strongly recommend handling potential display failures via `screenAd(_:didFailToPresentWithError:)` delegate to ensure a smoother user experience.

By relying on these delegate, you ensure that your application can react appropriately to real-time conditions, rather than making assumptions based on ad load state at a single point in time.

## Samples
- [SwiftUI AppOpen Ad ViewModel](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20SwiftUI/CASSwiftUIDemoApp/AppOpenAd/AppOpenAdModel.swift)
- [Swift AppOpen Ad UIViewController](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20Swift/CASSample/AppOpenAd/AppOpenVC.swift)
- [Objective-C AppOpen Ad UIViewController](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20Objective-C/CASSample/AppOpenAd/AppOpenVC.m)

## Cold starts and loading screens
The documentation thus far assumes that you only show app open ads when users foreground your app when it is suspended in memory. "Cold starts" occur when your app is launched but was not previously suspended in memory.  

An example of a cold start is when a user opens your app for the first time. With cold starts, you won't have a previously loaded app open ad that's ready to be shown right away. The delay between when you request an ad and receive an ad back can create a situation where users are able to briefly use your app before being surprised by an out of context ad. This should be avoided because it is a bad user experience.  

The preferred way to use app open ads on cold starts is to use a loading screen to load your game or app assets, and to only show the ad from the loading screen. If your app has completed loading and has sent the user to the main content of your app, do not show the ad.  

<Info>
In order to continue loading app assets while the app open ad is being displayed, always load assets in a background thread.
</Info>

## Best practices
App open ads help you monetize your app's loading screen, when the app first launches and during app switches, but it's important to keep best practices in mind so that your users enjoy using your app. It's best to:
- Show your first app open ad after your users have used your app a few times.
- Show app open ads during times when your users would otherwise be waiting for your app to load.
- If you have a loading screen under the app open ad, and your loading screen completes loading before the ad is dismissed, you may want to dismiss your loading screen in the `didDismissContent()` and `didFailToPresentWithError()` methods.
```

### Banner Ads

Source: https://production.docs.page/docs/ios/banner-ads

```mdx

Banner ad units display rectangular ads that occupy a portion of an app's layout. 
They can refresh automatically after a set period of time. 
This means users view a new ad at regular intervals, even if they stay on the same screen in your app. 
They're also the simplest ad format to implement.

Banner ads are displayed in `CASBannerView` objects, so the first step toward integrating banner ads is to include a `CASBannerView` in your view hierarchy. 
This is typically done either with the layout or programmatically.

Below is a diagram showing the ad lifecycle.
<Image zoom src="/assets/ios/Lifecycle-Banner-Ad.png" alt="Diagram" height="500" />


## Get the Ad size
To load a banner ad, you need to specify the ad size. To do this, choose one of the methods for obtaining an `CASSize` from the list below:
1. **Adaptive banner** ads have a fixed aspect ratio for the maximum width. The adaptive size calculates the optimal height for that width with an aspect ratio similar to 320x50.

<CodeGroup synchronize="true">
```swift
let adSize = AdSize.getAdaptiveBanner(forMaxWidth: 360)
```

```objc
CASSize *adSize = [CASSize getAdaptiveBannerForMaxWidth:360];
```
</CodeGroup>

2. **Inline banner** ads have a desired width and a maximum height, useful when you want to limit the banner's height. Inline banners are larger and taller compared to adaptive banners. They have variable height, including Medium Rectangle size, and can be as tall as the device screen.

<CodeGroup synchronize="true">
```swift
let adSize = CASSize.getInlineBanner(width: 360, maxHeight: 400)
```

```objc
CASSize *adSize = [CASSize getInlineBannerWithWidth:360 maxHeight:400];
```
</CodeGroup>

3. **Smart ad size** selects the optimal dimensions depending on the device type. For mobile devices, it returns 320x50, while for tablets, it returns 728x90. In the UI, these banners occupy the same amount of space regardless of device type.

<CodeGroup synchronize="true">
```swift
let adSize = CASSize.getSmartBanner()
```

```objc
CASSize *adSize = [CASSize getSmartBanner];
```
</CodeGroup>

4. **Medium Rectangle** has a fixed size of 300x250.

<CodeGroup synchronize="true">
```swift
let adSize = CASSize.mediumRectangle
```

```objc
CASSize *adSize = CASSize.mediumRectangle;
```
</CodeGroup>

5. **Leaderboard** has a fixed size of 728x90 and is allowed on tablets only.

<CodeGroup synchronize="true">

```swift
let adSize = CASSize.leaderboard
```

```objc
CASSize *adSize = CASSize.leaderboard;
```
</CodeGroup>

6. **Standard banner** has a fixed size of 320x50 and is the minimum ad size.

<CodeGroup synchronize="true">
```swift
let adSize = CASSize.banner
```

```objc
CASSize *adSize = CASSize.banner;
```
</CodeGroup>

## Create Ad View
The first step toward displaying a banner is to create `CASBannerView` in the layout. 

<Tabs>
<TabItem label="Programmatically" value="script">
The `CASBannerView` can be instantiated directly. In this case, we instantiate the banner with desired ad size and CAS ID.

<CodeGroup synchronize="true">
```swift
class MyViewController: UIViewController, CASBannerDelegate {
    var bannerView: CASBannerView!

   override func viewDidLoad() {
        super.viewDidLoad()                

        let adSize = CASSize.banner                

        bannerView = CASBannerView(casID: MyAppDelegate.casID, size: adSize, origin: .zero)
        bannerView.delegate = self
        bannerView.isAutoloadEnabled = true
        
        addBannerViewToView()
    }

    func addBannerViewToView() {
        bannerView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(bannerView)
        
        NSLayoutConstraint.activate([
            bannerView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            bannerView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        ])
    }
}
```

```objc
@interface MyViewController : UIViewController <CASBannerDelegate>
@property (nonatomic, strong) CASBannerView *bannerView;
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CASSize *adSize = CASSize.banner;
    self.bannerView = [[CASBannerView alloc] initWithCasID: MyAppDelegate.casID
                                                     size:adSize
                                                   origin:CGPointZero];
    self.bannerView.delegate = self;
    self.bannerView.isAutoloadEnabled = YES;
    
    [self addBannerViewToView];
}

- (void)addBannerViewToView {
    self.bannerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.bannerView];
    
    [NSLayoutConstraint activateConstraints:@[
        [self.bannerView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor],
        [self.bannerView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor]
    ]];
}

@end
```
</CodeGroup>

This example doesn't give width or height constraints, as the provided ad size gives the banner an intrinsic content size to size the view.

</TabItem>
<TabItem label="Interface Builder" value="builder">
You can add the `CASBannerView` module to a storyboard or xib file. 
When using this method, be sure to only add position constraints on the banner. 
For example, when displaying an adaptive banner at the bottom of the screen, 
set the bottom of the banner view equal to the top of the Bottom Layout Guide, 
and set the `centerX` constraint equal to the `centerX`of the superview.

The banner's ad size and CAS ID is still set programmatically:

<CodeGroup synchronize="true">
```swift
class MyViewController: UIViewController, CASBannerDelegate {
    @IBOutlet var bannerView: CASBannerView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let bannerDelegate: CASBannerDelegate = self
        bannerView.delegate = bannerDelegate
        bannerView.casID = MyAppDelegate.casID
        bannerView.adSize = AdSize...    
        bannerView.isAutoloadEnabled = true
    }
}
```

```objc
@interface MyViewController : UIViewController <CASBannerDelegate>
@property (weak, nonatomic) IBOutlet CASBannerView *bannerView;
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.bannerView.delegate = self;
    self.bannerView.casID = MyAppDelegate.casID;
    self.bannerView.adSize = CASSize.banner;
    self.bannerView.isAutoloadEnabled = YES;
}

@end
```
</CodeGroup>

</TabItem>
</Tabs>

<Info>
Banner ads view must be placed in the [Safe Area](https://developer.apple.com/ios/human-interface-guidelines/visual-design/adaptivity-and-layout/#layout-guides-and-safe-area) to avoid being obscured by rounded corners, sensor housing, and the Home indicator.
</Info>

## Receive Ad events
To further customize the behavior of your ad, you can hook onto a number of events in the ad's lifecycle: loading, failing, clicking, and so on. You can listen for these events through the `CASBannerDelegate` protocol.  

<CodeGroup synchronize="true">
```swift
func bannerAdViewDidLoad(_ view: CASBannerView) {
  // Invokes this callback when ad loaded and ready to present.
}

func bannerAdView(_ adView: CASBannerView, didFailWith error: CASError) {
  // Invokes this callback when an error occurred with the ad.
  // - To see a description of the error, see `CASError.message`.
}

func bannerAdViewDidRecordClick(_ adView: CASBannerView) {
  // Invokes this callback when a user clicks the ad.
}

func bannerAdView(_ adView: CASBannerView, willPresent impression: CASImpression) {
  // Legacy, same as new didRecordImpression(AdContentInfo).
}
```

```objc
- (void)bannerAdViewDidLoad:(CASBannerView *)view {
    // Invokes this callback when ad loaded and ready to present.
}

- (void)bannerAdView:(CASBannerView *)adView didFailWith:(CASError *)error {
    // Invokes this callback when an error occurred with the ad.
    // - To see a description of the error, see `CASError.message`.
}

- (void)bannerAdViewDidRecordClick:(CASBannerView *)adView {
    // Invokes this callback when a user clicks the ad.
}

- (void)bannerAdView:(CASBannerView *)adView willPresent:(id<CASStatusHandler> _Nonnull)impression {
    // Legacy, same as new didRecordImpression(AdContentInfo).
}
```
</CodeGroup>

Note that the reference to `delegate` is weak and can be removed from memory.

## Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements.

The placement name should be set before loading the ads. Maximum 100 characters allowed for the placement name.

<CodeGroup synchronize="true">
```swift
bannerView.placement = "BestPlace"
```

```objc
bannerView.placement = @"BestPlace";
```
</CodeGroup>

## Load Ad 
Once the ad view is in place, the next step is to load an ad. 
That's done with the `loadAd()` method in the `CASBannerView`class.

<CodeGroup synchronize="true">
```swift
bannerView.loadAd()
```

```objc
[bannerView loadAd];
```
</CodeGroup>

### Autoload Ad mode
If enabled, the ad will automatically load new content when the current ad is dismissed or completed. Additionally, it will automatically retry loading the ad if an error occurs during the loading process.  

<CodeGroup synchronize="true">
```swift
bannerView.isAutoloadEnabled = false
```

```objc
bannerView.isAutoloadEnabled = NO;
```
</CodeGroup>
By default enabled.

## Handle Orientation Changes
When using an `CASSize` based on screen width, you should recalculate the size whenever 
the device orientation changes and reload the banner ad to match the new layout.

<CodeGroup synchronize="true">
```swift
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    bannerView.adSize = AdSize...  
    if bannerView.isAutoloadEnabled == false {
      bannerView.loadAd()
    }
}
```

```objc
- (void)viewWillTransitionToSize:(CGSize)size
       withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    self.bannerView.adSize = [CASSize getAdaptiveBannerForMaxWidth:size.width];
    if (!self.bannerView.isAutoloadEnabled) {
        [self.bannerView loadAd];
    }
}
```
</CodeGroup>

## Banner Ad visibility
The banner is a normal view so you can feel free to change the visibility with the following method:

<CodeGroup synchronize="true">
```swift
bannerView.isHidden = true
```

```objc
bannerView.hidden = YES;
```
</CodeGroup>

## Ad refresh interval
The ad view’s automatic refresh interval determines how often a new ad request is generated for that ad view. You have the option to set a custom refresh interval longer than 10 seconds or to disable the Automatic refresh option for the ad view.

Change the banner automatic refresh interval using the following method:

<CodeGroup synchronize="true">
```swift
bannerView.refreshInterval = interval
```

```objc
bannerView.refreshInterval = interval;
```
</CodeGroup>

We recommend using optimal automatic refresh interval 30 seconds, by default.

To disable refresh ad use following method:

<CodeGroup synchronize="true">
```swift
bannerView.disableAdRefresh();
```

```objc
[self.bannerView disableAdRefresh];
```
</CodeGroup>

<Info>
- The automatic refresh occurs only if the banner is visible on screen.  
- The `isAutoloadEnabled` has no effect on refreshing the banner ad.
</Info>

## Release ad resource
Be sure to release ad resources if you’re no longer going to use the ad view.

<CodeGroup synchronize="true">
```swift
deinit {
  bannerView.destroy()
}
```

```objc
- (void)dealloc {
    [self.bannerView destroy];
}
```
</CodeGroup>

## Check Ad availability
Use `isAdLoaded` to check whether an ad is currently loaded.

<CodeGroup synchronize="true">
```swift
if bannerView.isAdLoaded {
  // ...
}
```

```objc
if (bannerView.isAdLoaded) {
  // ...
}
```
</CodeGroup>

## Samples
- [SwiftUI Banner Ad View](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20SwiftUI/CASSwiftUIDemoApp/BannersAd/BannerAdView.swift)
- [SwiftUI Adaptive Banner Ad Container View](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20SwiftUI/CASSwiftUIDemoApp/BannersAd/AdaptiveBannerContainerView.swift)
- [Swift Banner Ad UIViewController](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20Swift/CASSample/BannerAd/BannerVC.swift)
- [Objective-C Banner Ad UIViewController](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20Objective-C/CASSample/BannerAd/BannerVC.m)
```

### Display Native Ad

Source: https://production.docs.page/docs/ios/display-native-ad

```mdx

For the Native Ad format, there is the corresponding `CASNativeView` class. This class is a `UIView` that publishers should use as the root for the `NativeAdContent`. A single `CASNativeView` corresponds to a single native ad. Each view used to display that ad's assets (the `UIImageView` that displays the screenshot asset, for instance) should be a child of the `CASNativeView` object.

Here are the individual tasks:
<Steps>
<Step title="Inflate the layout">
See below how you can layout the views using Templates or Manual. 
</Step>
<Step title="Register the asset views">
See below how you can register the asset views using Templates or Manual.
Values for registered views will be set automatically when calling `bindAdContent()`.  
Note that views for which the loaded ad does not provide content will be hidden with `view.isHidden = true`.
</Step>
<Step title="Handle clicks">
Don't implement any custom click handlers on any views over or within the native ad view. To observe click events yourself, use the ad delegate `nativeAdDidClickContent`. Clicks on the ad view assets are handled by the SDK as long as you correctly populate and register the asset views, as discussed in the previous section.
</Step>
<Step title="Register the native ad content">
This final step registers the native ad object with the view that's responsible for displaying it. Note that you can also reuse an existing `CASNativeView` if one is already present in your fragment or activity, or you can create an instance dynamically without using a layout file. Simply call `bindAdContent` for each new `NativeAdContent`.

<CodeGroup synchronize="true">
```swift
func registerNativeAdContent(_ nativeAd: NativeAdContent) {
    adView.bindAdContent(nativeAd)
}
```

```objc
- (void)registerNativeAdContent:(CASNativeAdContent *)nativeAd {
    [self.adView bindAdContent:nativeAd];
}
```
</CodeGroup>

<Warning>  
The `bindAdContent(NativeAdContent)` method must be called from the main (UI) thread.
</Warning>

</Step>
</Steps>

## Validate Ad Content (Optional)
Native ads can be preloaded and cached to reduce latency when displaying ads to users. However, these ads have a limited lifespan and may expire after a certain period. To ensure a seamless user experience, you should validate the ad content before displaying it.

Use the `NativeAdContent.isExpired` property to check if the ad has expired. If you attempt to display an expired ad, it will trigger an `nativeAd(_:didFailToPresentWithError)` callback.

<CodeGroup synchronize="true">
```swift
func registerNativeAdContent(_ nativeAd: NativeAdContent) {
    if nativeAd.isExpired {
        loadNativeAds()
        return
    }
    
    adView.bindAdContent(nativeAd)
}
```

```objc
- (void)registerNativeAdContent:(CASNativeAdContent *)nativeAd {
    if (nativeAd.isExpired) {
        [self loadNativeAds];
        return;
    }

    [self.adView bindAdContent:nativeAd];
}
```
</CodeGroup>

If you display the ad immediately in `nativeAdDidLoadContent(_:)`, there's no need to check its validity, as it is guaranteed to be fresh at that moment. 

## Display native ad Templates
### Layout the views
The easiest way to integrate native ads into your app is via the templates API. You just need to create the empty `CASNativeView`, add ad view to layout and `setAdTemplateSize`.

<CodeGroup synchronize="true">
```swift
@IBOutlet var adView: CASNativeView!
    
override func viewDidLoad() {
    super.viewDidLoad()
    loadNativeAds()
    
    let size = AdSize.mediumRectangle
    adView.setAdTemplateSize(size)

    customizeAdViewAppearance(adView)
}
```

```objc
@interface MyViewController: UIViewController
@property (weak, nonatomic) IBOutlet CASNativeView *adView;
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadNativeAds];

    CASSize *size = CASSize.mediumRectangle;
    [self.adView setAdTemplateSize:size];

    [self customizeAdViewAppearance: self.adView];
}
@end
```
</CodeGroup>

<Info>
Creating the layout may cause UI rendering to freeze briefly, so it is recommended to set the template size only once when initializing the view.  
The `setAdTemplateSize(AdSize)` method must be called from the main (UI) thread.
</Info>

**Optional:** Customize the appearance of asset views after calling `setAdTemplateSize` by modifying properties from the `CASNativeView`.

<CodeGroup synchronize="true">
```swift
fun customizeAdViewAppearance(_ adView: CASNativeView) {
    // Default values are shown below:
    adView.backgroundColor = UIColor.white
    adView.callToActionView?.configuration?.baseBackgroundColor = UIColor.tintColor
    adView.headlineView?.textColor = UIColor.darkText
}
```

```objc
- (void)customizeAdViewAppearance:(CASNativeView *)adView {
    // Default values are shown below:
    adView.backgroundColor = UIColor.whiteColor;
    adView.callToActionView.configuration.baseBackgroundColor = UIColor.tintColor;
    adView.headlineView.textColor = UIColor.darkTextColor;
}
```
</CodeGroup>

### Register the asset views
When you set the ad template size using `setAdTemplateSize(_:)`, the `CASNativeView` automatically registers all ad asset views with the corresponding template assets for the selected size. 

## Manual display native ad

### Layout the views
The first step is to lay out the `UIViews` that will display native ad assets. You can do this in the Interface Builder as you would when creating any other xib file. 

The Custom Class value it's set to `CASNativeView`. This is the ad view class that is used to display a `NativeAdContent`.

<Image width="257" alt="Image" src="/assets/ios/Native-NativeView.png" />

You'll also need to set the custom class for the `CASMediaView`, which is used to display the video or image for the ad.

<Image width="262" alt="Image" src="/assets/ios/Native-MediaView.png" />

### Register the asset views 
Register the asset views lets the SDK know which `UIView` displays which asset. It's also important to remember that these outlets represent the views that are clickable in the ad.

#### Register the asset views using view tags
Assign unique tag IDs to the asset views. The example image below sets the ID to `100` for the Media View.

<Image width="298" alt="Image" src="/assets/ios/Native-ViewTags.png" />

In your ViewController code, assign each created view using unique tag IDs for ad assets to the corresponding properties of `CASNativeView`.

<CodeGroup synchronize="true">
```swift
@IBOutlet var adView: CASNativeView!
    
override func viewDidLoad() {
    super.viewDidLoad()
    loadNativeAds()

    registerAdAsetViews()
}

func registerAdAsetViews() {
    // You can also omit adChoicesView and it will be created automatically.
    adView.registerAdChoicesView(tag: 99)

    adView.registerMediaView(tag: 100)
    adView.registerIconView(tag: 101)
    adView.registerHeadlineView(tag: 102)
    adView.registerAdLabelView(tag: 103)
    adView.registerBodyView(tag: 104)
    adView.registerCallToActionView(tag: 105)
    adView.registerAdvertiserView(tag: 106)
    adView.registerStoreView(tag: 107)
    adView.registerPriceView(tag: 108)
    adView.registerStarRatingView(tag: 109)
    adView.registerReviewCountView(tag: 110)
}
```

```objc
- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadNativeAds];
    [self registerAdAssetViews];
}

- (void)registerAdAssetViews {
    [self.adView registerAdChoicesViewWithTag:99];
    [self.adView registerMediaViewWithTag:100];
    [self.adView registerIconViewWithTag:101];
    [self.adView registerHeadlineViewWithTag:102];
    [self.adView registerAdLabelViewWithTag:103];
    [self.adView registerBodyViewWithTag:104];
    [self.adView registerCallToActionViewWithTag:105];
    [self.adView registerAdvertiserViewWithTag:106];
    [self.adView registerStoreViewWithTag:107];
    [self.adView registerPriceViewWithTag:108];
    [self.adView registerStarRatingViewWithTag:109];
    [self.adView registerReviewCountViewWithTag:110];
}
```
</CodeGroup>

#### Register the asset views using outlets
Once the views are in place and you've assigned the correct ad view class to the layout, link the ad view's asset outlets to your ViewController. Here's how you might link the ad view's asset outlets to the `UIViews` created for an ad:

<Image width="255" alt="Image" src="/assets/ios/Display-Native-Ad-4.png" />

In your ViewController code, assign each created view for ad assets to the corresponding properties of `CASNativeView`.

<CodeGroup synchronize="true">
```swift
@IBOutlet var adView: CASNativeView!

@IBOutlet var mediaView: CASMediaView!
@IBOutlet var adChoicesView: CASChoicesView?
@IBOutlet var adLabelView: UILabel!
@IBOutlet var headlineView: UILabel!
@IBOutlet var callToActionView: UIButton!
@IBOutlet var iconView: UIImageView!
@IBOutlet var bodyView: UILabel!
@IBOutlet var priceView: UILabel!
@IBOutlet var advertiserView: UILabel!
@IBOutlet var storeView: UILabel!
@IBOutlet var starRatingView: UIView!
@IBOutlet var reviewCountView: UILabel!
    
override func viewDidLoad() {
    super.viewDidLoad()
    loadNativeAds()

    registerAdAsetViews()
}

func registerAdAsetViews() {
    // You can also omit adChoicesView and it will be created automatically.
    adView.adChoicesView = adChoicesView

    adView.mediaView = mediaView
    adView.adLabelView = adLabelView
    adView.headlineView = headlineView
    adView.callToActionView = callToActionView
    adView.iconView = iconView
    adView.bodyView = bodyView
    adView.priceView = priceView
    adView.advertiserView = advertiserView
    adView.storeView = storeView
    adView.starRatingView = starRatingView
    adView.reviewCountView = reviewCountView
}
```

```objc
@interface MyViewController: UIViewController
@property (weak, nonatomic) IBOutlet CASNativeView *adView;
@property (weak, nonatomic) IBOutlet CASMediaView *mediaView;
@property (weak, nonatomic) IBOutlet CASChoicesView *adChoicesView;
@property (weak, nonatomic) IBOutlet UILabel *adLabelView;
@property (weak, nonatomic) IBOutlet UILabel *headlineView;
@property (weak, nonatomic) IBOutlet UIButton *callToActionView;
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *bodyView;
@property (weak, nonatomic) IBOutlet UILabel *priceView;
@property (weak, nonatomic) IBOutlet UILabel *advertiserView;
@property (weak, nonatomic) IBOutlet UILabel *storeView;
@property (weak, nonatomic) IBOutlet UIView *starRatingView;
@property (weak, nonatomic) IBOutlet UILabel *reviewCountView;
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadNativeAds];
    [self registerAdAssetViews];
}

- (void)registerAdAssetViews {
    self.adView.adChoicesView = self.adChoicesView;
    self.adView.mediaView = self.mediaView;
    self.adView.adLabelView = self.adLabelView;
    self.adView.headlineView = self.headlineView;
    self.adView.callToActionView = self.callToActionView;
    self.adView.iconView = self.iconView;
    self.adView.bodyView = self.bodyView;
    self.adView.priceView = self.priceView;
    self.adView.advertiserView = self.advertiserView;
    self.adView.storeView = self.storeView;
    self.adView.starRatingView = self.starRatingView;
    self.adView.reviewCountView = self.reviewCountView;
}
@end
```
</CodeGroup>

## Samples
- SwiftUI:
    -  [Native Ad View (manual)](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20SwiftUI/CASSwiftUIDemoApp/NativeAd/NativeAdView.swift)
    -  [Native Ad Template View](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20SwiftUI/CASSwiftUIDemoApp/NativeAd/NativeAdTemplateView.swift)
- Swift:
    -  [Native Ad View (manual)](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20Swift/CASSample/NativeAd/NativeVC.swift)
    -  [Native Ad Template View](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20Swift/CASSample/NativeAd/NativeTemplateVC.swift)
- Objective-C:
    -  [Native Ad View (manual)](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20Objective-C/CASSample/NativeAd/NativeVC.m)
    -  [Native Ad Template View](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20Objective-C/CASSample/NativeAd/NativeTemplateVC.m)
```

### Enabling test ads

Source: https://production.docs.page/docs/ios/enabling-test-ads

```mdx

It's important to enable test ads during development so that you can click on them without charging CAS advertisers.

<Error>  
We strongly suggest that you enable test ads mode when you validate the integration.  If you click on too many ads without being in test mode, you risk your account being flagged for invalid activity.
</Error>

There are two ways to get test ads:
- [Enable test ad mode](ios/enabling-test-ads#enable-test-ad-mode) for all devices.
- [Set device ids to test ad](ios/enabling-test-ads#enable-test-devices).

Ads with Test Ads mode are safe to click. Requests, impressions, and clicks on test ads will not show up in your account's reports.  
Test full-screen ads displays details of CAS integration and tips for solving errors. Go to the Mediation Adapters section to make sure that the advertising networks you want are integrated correctly.

<Image height="500" alt="image" src="/assets/Enabling-test-ads-1.jpg" />
<Image height="500" alt="image" src="/assets/Enabling-test-ads-2.jpg" />


## Enable Debug log mode
The enabled Debug Mode will display a lot of useful information for debugging about the states of the sdk with tag CAS.   
Disabled by default. Disabling Debug Mode may improve application performance.  

<CodeGroup synchronize="true">
```swift
CAS.settings.debugMode = true
```

```objc
CAS.settings.debugMode = YES;
```
</CodeGroup>

<Info>
If you have discovered the problem in the work of the SDK, please provide us with a description of the problem along with the full log of your device.
</Info>

## Enable test ad mode
The quickest way to enable testing is to use test ad mode. The test ad mode are not associated with your CAS account, so there's no risk of your account generating invalid traffic when using these test ad mode.

The easiest way to load test ads is to use:

<CodeGroup synchronize="true">
```swift
buildManager.withTestAdMode(true)
```

```objc
[buildManager withTestAdMode:YES];
```
</CodeGroup>

<Warning>  
Make sure you disable test ad mode and replace test manager ID with your own ad manager ID before publishing your app!
</Warning>

## Enable test devices
If you want to do more rigorous testing with production-looking ads, you can now configure your device as a test device and use your own manager id. Test devices can either be added programmatically.

Follow the steps below to add your device as a test device.
1. Run an app configured with the CAS on device.
2. Check the console output for a message that looks like this:
```
To get test ads on this device, set "12345678901234567890123456789012"
```
3. Copy your alphanumeric test device ID to your clipboard.
4. Modify your code to set the test device ID through add `TestDeviceIDs` before CAS manager initialize.

<CodeGroup synchronize="true">
```swift
CAS.settings.setTestDevice(ids: ["12345678901234567890123456789012"])
```

```objc
[CAS.settings setTestDeviceWithIds:@[@"12345678901234567890123456789012"]];
```
</CodeGroup>

<Info>
Be sure to remove the code that sets these test devices before you release your app.  
</Info>

5. Re-run your app. 
6. Well done, ads on this device are safe to click. Requests, impressions, and clicks on ads in test mode will not show up in your account's reports.
```

### Impression Level Data

Source: https://production.docs.page/docs/ios/impression-level-data

```mdx

CAS.AI SDK enables you to access detailed information for each impression through the impressions callback APIs. The information includes, for example, which demand source served the ad, the expected or exact revenue associated with it. In addition, it contains granular details to allow you to analyze and, ultimately, optimize user acquisition strategies. 

## AdContentInfo
The `AdContentInfo` data structure, which contains information about the loaded/displayed ad. 

Additionally to `impressionDelegate`, each ad format has a `contentInfo` property that returns `AdContentInfo`, but the info may be `nil` before the ad is loaded.

<CodeGroup synchronize="true">
```swift
let info: CASContentInfo? = eachAd.contentInfo
```

```objc
CASContentInfo *info = eachAd.contentInfo;
```
</CodeGroup>

<Property name="format" type="AdFormat">
  The format of the ad that is shown.
</Property>

---

<Property name="sourceName" type="String">
  The display name of the mediated network that purchased the impression.
</Property>

---

<Property name="sourceId" type="AdSource">
  The ID of the mediated network that purchased the impression.
</Property>

---

<Property name="sourceUnitId" type="String">
  The Ad Unit ID from the mediated network that purchased the impression.
</Property>

---

<Property name="creativeId" type="String?" optional>
  The Creative ID associated with the ad, if available.
  You can use this ID to report creative issues to the Ad review team. 
</Property>

---

<Property name="revenue" type="Double">
  The revenue generated from the impression, in USD. 
  The revenue value may be either estimated or exact, depending on the precision specified by `revenuePrecision`. 
</Property>

---

<Property name="revenuePrecision" type="AdRevenuePrecision">
  The precision type of the revenue field.
</Property>

---

<Property name="revenueTotal" type="Double">
  The accumulated value of user ad revenue in USD from all ad format impressions. 
</Property>

---

<Property name="impressionDepth" type="Int">
  The total number of impressions across all ad formats for the current user, across all sessions. 
</Property>

### User ad summary 
CAS count the number of ad impressions and the total revenue of all formats at the time of a new impression. 
<CodeGroup synchronize="true">
```swift
let totalImpressions: Int = impression.impressionDepth
let totalRevenue: Double = impression.revenueTotal
```

```objc
NSInteger totalImpressions = impression.impressionDepth;
double totalRevenue = impression.revenueTotal;
```
</CodeGroup>

<Info>
Progress is saved between sessions until the user clears your app's data.
</Info>

### OnAdImpressionListener
A delegate for receive ad impression info from each ad format.

<CodeGroup synchronize="true">
```swift
import CleverAdsSolutions

extension MyViewController: CASImpressionDelegate {
    func adDidRecordImpression(info: CASContentInfo) {
        // Called when an ad impression occurs. 
    }
}
```

```objc
#import <CleverAdsSolutions/CleverAdsSolutions.h>

@interface MyViewController: UIViewController <CASImpressionDelegate>
@end

@implementation MyViewController

- (void)adDidRecordImpression:(CASContentInfo *)info {
    // Called when an ad impression occurs.
}

@end
```
</CodeGroup>

Each ad format have a `weak var impressionDelegate` property to receive `AdContentInfo` with impression details.  

<CodeGroup synchronize="true">
```swift
let impressionDelegate: CASImpressionDelegate = self

let appOpenAd: CASAppOpen
appOpenAd.impressionDelegate = impressionDelegate

let interstitialAd: CASInterstitial
interstitialAd.impressionDelegate = impressionDelegate

let rewardedAd: CASRewarded
rewardedAd.impressionDelegate = impressionDelegate

let nativeAd: NativeAdContent
nativeAd.impressionDelegate = impressionDelegate
```

```objc
id<CASImpressionDelegate> impressionDelegate = self;

CASAppOpen *appOpenAd;
appOpenAd.impressionDelegate = impressionDelegate;

CASInterstitial *interstitialAd;
interstitialAd.impressionDelegate = impressionDelegate;

CASRewarded *rewardedAd;
rewardedAd.impressionDelegate = impressionDelegate;

CASNativeAdContent *nativeAd;
nativeAd.impressionDelegate = impressionDelegate;
```
</CodeGroup>

## Automatic collect ad revenue
The CAS SDK have features to automatically collect ad revenue to Google Analytics and Tenjin Analytics. Contact your account manager for details of enabling automatic events.
### Google Analytics
If you haven't already, make sure to complete the following tasks:
1. Set up your project and app as described in [Get Started with Analytics](https://firebase.google.com/docs/analytics/get-started).
2. Make sure that you've linked your Firebase project to a Google Analytics account.
3. Ensure that you've included in your app the CAS SDK 3.5.0+.

To measure ad revenue, CAS SDK log [`ad_impression` events](https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#public-static-final-string-ad_impression) whenever your user sees an advertisement in your app. These events contain details such as the ad platform, source, currency, and value. Optionally, the alternative event name can be `CAS_Impression`.  

### Tenjin
To measure ad revenue with Tenjin Analytics integrate the [Tenjin SDK](https://docs.tenjin.com/docs/ios-sdk#sdk-integration) or just include Tenjin SDK by CAS Cocoapods:
```ruby
pod 'CleverAdsSolutions-SDK/Tenjin', '{{ versions.ios }}'
```

<Info>
The Tenjin subspec is available through CocoaPods only. With Swift Package Manager, integrate the [Tenjin SDK](https://docs.tenjin.com/docs/ios-sdk#sdk-integration) directly.
</Info>

CAS SDK automatically initializes the Tenjin SDK and sends ILRD if this option is enabled for your application.

## Custom collect ad revenue
The following code shows an implementation example for log `ad_impression` event to Google Analytics.

<CodeGroup synchronize="true">
```swift
extension MyViewController: CASImpressionDelegate {
    func adDidRecordImpression(info: AdContentInfo) {
        Analytics.logEvent(
           AnalyticsEventAdImpression,
           parameters: [
               AnalyticsParameterAdPlatform: "CAS",
               AnalyticsParameterAdSource: info.sourceName,
               AnalyticsParameterAdUnitName: info.sourceUnitID,
               AnalyticsParameterAdFormat: info.format.description,
               AnalyticsParameterValue: info.revenue,
               // All CAS revenue is sent in USD
               AnalyticsParameterCurrency: "USD",
           ])
   }
}
```

```objc
#import <FirebaseAnalytics/FirebaseAnalytics.h>

@interface MyViewController: UIViewController <CASImpressionDelegate>
@end

@implementation MyViewController

- (void)adDidRecordImpression:(CASContentInfo *)info {
    [FIRAnalytics logEventWithName:kFIREventAdImpression
                        parameters:@{
        kFIRParameterAdPlatform: @"CAS",
        kFIRParameterAdSource: info.sourceName ?: @"",
        kFIRParameterAdUnitName: info.sourceUnitID ?: @"",
        kFIRParameterAdFormat: info.format.description ?: @"",
        kFIRParameterValue: @(info.revenue),
        // All CAS revenue is sent in USD
        kFIRParameterCurrency: @"USD"
    }];
}

@end
```
</CodeGroup>
```

### Initialize CAS Framework

Source: https://production.docs.page/docs/ios/initialize-cas

```mdx

The `initializeCAS()` method initializes the SDK and invokes a completion handler once the CAS SDK has been successfully initialized.
This should be done only once, ideally during the app launch.

To begin, create a string constant with your `casID`. This constant will be needed when creating each ad format instance.

<CodeGroup synchronize="true">
```swift
import CleverAdsSolutions

@main
class AppDelegate: UIResponder, UIApplicationDelegate { 
  static let casID: String = "demo"
    
  var window: UIWindow? // required for some mediated ads frameworks

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {    
    initializeCAS()
    return true
  }
  // ...
}

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
  var window: UIWindow?
  // ...
}
```

```objc
@import CleverAdsSolutions;

@implementation AppDelegate

+ (NSString *)casId {
    return @"demo";
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self initializeCAS];
    return YES;
}
```
</CodeGroup>

<AccordionGroup>
<Accordion title="What is CAS ID?">

In most cases, a CASID is the same as your app store ID.  
You can find an app store ID in the URL of your app’s Apple App Store URL. For example, the URL is `apps.apple.com/us/app/id123456789` then app store ID is `123456789`.  
 
If you haven't created an CAS account and registered an app yet, now's a great time to do so at https://cas.ai  
If you just want to experiment or test the SDK, you can skip the configuration your project.

</Accordion>
</AccordionGroup>

You can skip the manual call for ad initialization, and then the SDK will automatically perform the initialization before the first ad load. However, if it's important for you to change the configuration or listen to states of the Consent Flow, make sure to initialize it at least once before the first ad load.

<CodeGroup synchronize="true">
```swift
func initializeCAS() {
  let builder = CAS.buildManager()
  builder.withCompletionHandler { config in
    // The CAS SDK initializes if the error is `nil`
    let error: String? = config.error
    let userCountryISO2: String? = config.countryCode
        
    // True if the user is protected by GDPR or other regulations
    let protectionApplied: Bool = config.isConsentRequired
        
    // The user completes the consent flow
    let consentStatus = config.consentFlowStatus
    let trackingAuthorized: Bool = config.isATTrackingAuthorized
  }
        
  builder.create(withCasId: AppDelegate.casID)
}
```

```objc
- (void)initializeCAS {
  CASManagerBuilder *builder = [CAS buildManager];
    
  [builder withCompletionHandler:^(CASInitialConfig *config) {
    // The CAS SDK initializes if the error is `nil`
    NSString *error = config.error;
    NSString *userCountryISO2 = config.countryCode;

    // YES if the user is protected by GDPR or other regulations
    BOOL protectionApplied = config.isConsentRequired;

    // The user completes the consent flow
    CASConsentFlowStatus consentStatus = config.consentFlowStatus;
    BOOL trackingAuthorized = config.isATTrackingAuthorized;
  }];
        
  [builder createWithCasId:[AppDelegate casId]];
}
```
</CodeGroup>

The `withCompletionHandler` may be called with an error. In this case, the SDK will attempt to reinitialize and the listener will be called again until the error is resolved.

<Error>  
Do not initialize mediated advertising SDKs (CAS does that for you).  
Not following this step will result in noticeable integration issues.
</Error>

### SwiftUI support
To handle app delegate callbacks in an app that uses the SwiftUI lifecycle, you must create an application delegate and attach it to your `App` struct using `UIApplicationDelegateAdaptor`.
```swift
@main
struct YourApp: App {
  @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

  var body: some Scene {
    WindowGroup {
      NavigationView {
        ContentView()
      }
    }
  }
}
```

## Automatic user consent flow
To get consent for collecting personal data of your users, we suggest you use a built-in Consent Flow, comes with a pre-made consent form that you can easily present to your users. That means you no longer need to create your own consent window.  

The user will see the consent flow when your app initialize CAS SDK. When the user completes the flow, the SDK calls your initialization-completion handler.

CAS consent flow is enabled by default. You can disable the consent flow by add disabled  `CASConsentFlow` to `withConsentFlow()`:

<CodeGroup synchronize="true">
```swift
builder.withConsentFlow(
    CASConsentFlow(isEnabled: false)
)
```

```objc
CASConsentFlow *consentFlow = [[CASConsentFlow alloc] initWithEnabled:NO];
[builder withConsentFlow:consentFlow];
```
</CodeGroup>

Make sure to apply all configurations before calling `builder.build()`.

You must wait until the user finishes the consent flow before you initialize third-party SDKs (such as MMPs or analytics SDKs). For this reason, initialize such SDKs from within your initialization-completion callback. If you were to initialize these third-party SDKs before the user completes the consent flow, these third-party SDKs would not be able to access relevant identifiers and you would suffer a material impact on measurement, reporting, and ad revenue.

<Info>
Read more about "Privacy options button" and "Debug geography" on [CAS User Consent Flow page](ios/user-consent-flow)
</Info>

## Always test with test ads
When building and testing your apps, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account.

By default, CAS initializes mediation in live mode. To enable test ad mode, you should manually call `initializeCAS()` with the following option:

<CodeGroup synchronize="true">
```swift
#if DEBUG
  builder.withTestAdMode(true)
#endif
```

```objc
#ifdef DEBUG
  [builder withTestAdMode:YES];
#endif
```
</CodeGroup>

For more information about how the CAS.AI SDK's test ads work, see [Enable test ads](ios/enabling-test-ads)

## Prohibition on Personal Information from Children
Apps can be marked as child-directed or [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy) applicable through the CAS UI.  

If the app determines that a user falls under COPPA regulations, the `taggedAudience` must be called before initializing the CAS SDK.

<CodeGroup synchronize="true">
```swift
CAS.settings.taggedAudience = CASAudience.children
```

```objc
CAS.settings.taggedAudience = CASAudienceNotChildren;
```
</CodeGroup>

If your app targets both children and older users, all ads that may be shown to children must comply with COPPA.  
To ensure compliance, a **neutral age screen** must be implemented so that ads unsuitable for children are only shown to appropriate audiences.  
A neutral age screen is a tool—such as an age gate—that verifies a user’s age without encouraging them to misrepresent it, and prevents children from accessing content not intended for them.


## (Optional) Legacy support MediationManager
We are not removing support for managing ads using `CASMediationManager` at this time, but we recommend migrating to the new `CASInterstitial` and `CASRewarded` components whenever possible.

To continue using `MediationManager`, you still need to specify the ad formats you want to work with, just as before.  

<CodeGroup synchronize="true">
```swift
builder.withAdTypes(CASType.interstitial, CASType.rewarded)
```

```objc
[builder withAdFlags:CASTypeFlagsInterstitial | CASTypeFlagsRewarded];
```
</CodeGroup>

If your app no longer uses `CASMediationManager` for Interstitial and Rewarded formats, simply do not define any formats during initialization.

## (Optional) Retrieve the Version Number
To programmatically retrieve the SDK version number at runtime, CAS provides the following method:

<CodeGroup synchronize="true">
```swift
String sdkVersion = CAS.getSDKVersion();
```

```objc
NSString *sdkVersion = [CAS getSDKVersion];
```
</CodeGroup>

## (Optional) Trial ad-free interval
Set the time interval during which users can enjoy an ad-free experience while retaining access
to Rewarded Ads and App Open Ads formats. This interval is defined from the moment of the initial
app installation, in seconds. Within this interval, users enjoy privileged access to the
application's features without intrusive advertisements.

<CodeGroup synchronize="true">
```swift
let secondsIn7Days = 604800
CAS.settings.trialAdFreeInterval = secondsIn7Days
```

```objc
NSInteger secondsIn7Days = 604800;
CAS.settings.trialAdFreeInterval = secondsIn7Days;
```
</CodeGroup>

## Complete sample
- [Swift Sample Application](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20Swift/CASSample/AppDelegate.swift)
- [SwiftUI Sample Application](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20SwiftUI/CASSwiftUIDemoApp/AppDelegate.swift)
- [Objective-C Sample Application](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20Objective-C/CASSample/AppDelegate.m)
```

### Interstitial Ads

Source: https://production.docs.page/docs/ios/interstitial-ads

```mdx

Interstitial ads are full-screen ads that cover the interface of their host app. 
They're typically displayed at natural transition points in the flow of an app, such as between screens or during the pause between levels in a game. 
When an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.  

Below is a diagram showing the ad lifecycle.
<Image zoom src="/assets/ios/Lifecycle-Screen-Ad.png" alt="Diagram" height="500" />


## Create Ad instance
Ad instance can be initialized along with the UIViewController before `viewDidLoad`.

<CodeGroup synchronize="true">
```swift
import CleverAdsSolutions

class MyViewController: UIViewController, CASScreenContentDelegate {

    let interstitialAd = CASInterstitial(casID: MyAppDelegate.casID)

```

```objc
#import <CleverAdsSolutions/CleverAdsSolutions.h>

@interface MyViewController : UIViewController <CASScreenContentDelegate>
@property (nonatomic, strong) CASInterstitial *rewardedAd;
@end

@implementation MyViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        _rewardedAd = [[CASInterstitial alloc] initWithCasID:MyAppDelegate.casID];
    }
    return self;
}

@end
```
</CodeGroup>

The SDK provides the capability to create and precache multiple ad instances, enabling uninterrupted sequential ad display. CAS SDK will load mediation ads in order for each created instance.
## Receive Ad events
The `CASScreenContentDelegate` handles events related to displaying your `CASInterstitial`. Callbacks are called on the main thread. Before showing ad, make sure to set `delegate`.

<CodeGroup synchronize="true">
```swift
func screenAdDidLoadContent(_ ad: any CASScreenContent) {
    // Called when the ad content has been successfully loaded.
}

func screenAd(_ ad: any CASScreenContent, didFailToLoadWithError error: AdError) {
    // Called when the ad content fails to load.
}

func screenAd(_ ad: any CASScreenContent, didFailToPresentWithError error: AdError) {
    // Called when the ad content fails to present.
}

func screenAdWillPresentContent(_ ad: any CASScreenContent) {
    // Called when the ad content is successfully shown.
}

func screenAdDidClickContent(_ ad: any CASScreenContent) {
    // Called when the ad content is clicked by the user.
}

func screenAdDidDismissContent(_ ad: any CASScreenContent) {
    // Called when the ad content is dismissed.
}
```

```objc
- (void)screenAdDidLoadContent:(id<CASScreenContent>)ad {
    // Called when the ad content has been successfully loaded.
}

- (void)screenAd:(id<CASScreenContent>)ad didFailToLoadWithError:(CASError *)error {
    // Called when the ad content fails to load.
}

- (void)screenAd:(id<CASScreenContent>)ad didFailToPresentWithError:(CASError *)error {
    // Called when the ad content fails to present.
}

- (void)screenAdWillPresentContent:(id<CASScreenContent>)ad {
    // Called when the ad content is successfully shown.
}

- (void)screenAdDidClickContent:(id<CASScreenContent>)ad {
    // Called when the ad content is clicked by the user.
}

- (void)screenAdDidDismissContent:(id<CASScreenContent>)ad {
    // Called when the ad content is dismissed.
}

```
</CodeGroup>

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](ios/impression-level-data).
- Attempting to load a new ad from the `didFailToLoadWithError` method is strongly discouraged. Limit ad load retries to avoid continuous failed ad requests in situations such as limited network connectivity.
- When an error occurs during ad impression, executed the `didFailToPresentWithError` only.  In this case the `didDismissContent` will not be executed, since the impression is not considered successful.
</Info>

## Load Ad
The next step is to fill out the `loadAd()` method and handle the ad load callbacks.

<CodeGroup synchronize="true">
```swift
override func viewDidLoad() {
    super.viewDidLoad()

    let screenContentDelegate: CASScreenContentDelegate = self
    interstitialAd.delegate = screenContentDelegate
    interstitialAd.loadAd();
}
```

```objc
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.interstitialAd = [[CASInterstitial alloc] initWithCasID: MyAppDelegate.casID];
    self.interstitialAd.delegate = self;
    
    [self.interstitialAd loadAd];
}
```
</CodeGroup>

You can use ad load calls to build up a cache of preloaded ads before you intend to show them, so that ads can be shown with zero latency when needed. Since ads expire after an hour, you should clear this cache and reload with new ads every hour.

### Autoload mode
If enabled, the ad will automatically load new content when the current ad is dismissed or completed. Additionally, it will automatically retry loading the ad if an error occurs during the loading process.  

<CodeGroup synchronize="true">
```swift
override func viewDidLoad() {
    super.viewDidLoad()

    let screenContentDelegate: CASScreenContentDelegate = self
    interstitialAd.delegate = screenContentDelegate
    interstitialAd.isAutoloadEnabled = true;
}
```

```objc
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.interstitialAd.delegate = self;
    self.interstitialAd.isAutoloadEnabled = YES;     
}
```
</CodeGroup>

By default autoload disabled.

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements.

The placement name should be set before showing the ads. Maximum 100 characters allowed for the placement name.

<CodeGroup synchronize="true">
```swift
interstitialAd.placement = "BestPlace"
```

```objc
interstitialAd.placement = @"BestPlace";
```
</CodeGroup>

## Show Ad
Interstitial ads should be displayed during natural pauses in the flow of an app. Between levels of a game is a good example, or after the user completes a task. 

<CodeGroup synchronize="true">
```swift
interstitialAd.present(from: self);
```

```objc
[self.interstitialAd presentFromViewController: self];
```
</CodeGroup>

The `UIViewController` parameter is an optional. The SDK uses the app’s main window to look up view controllers automatically when one is not provided.

Starting with CAS SDK version 4.3.0, all ads functions can be safely called from any thread.

### Autoshow mode
Use the `isAutoshowEnabled` property to automatically show a loaded ad when the user returns to the app.

<CodeGroup synchronize="true">
```swift
override func viewDidLoad() {
    super.viewDidLoad()
    // ...    
    interstitialAd.isAutoshowEnabled = true
}
```

```objc
- (void)viewDidLoad {
    [super viewDidLoad];
    // ...    
    self.interstitialAd.isAutoshowEnabled = YES;
}
```
</CodeGroup>

By default autoshow disabled.

### Checking Ad Availability
Use `isAdLoaded` to check whether an ad is currently loaded.

<CodeGroup synchronize="true">
```swift
if interstitialAd.isAdLoaded {
    // ...
}
```

```objc
if (interstitialAd.isAdLoaded) {
    // ...
}
```
</CodeGroup>

Even if `isAdLoaded` returns `true`, it does not guarantee that the ad will be shown successfully — various issues may still prevent it from being displayed. We strongly recommend handling potential display failures via `screenAd(_:didFailToPresentWithError:)` delegate to ensure a smoother user experience.

By relying on these delegate, you ensure that your application can react appropriately to real-time conditions, rather than making assumptions based on ad load state at a single point in time.

## Minimum interval between impressions
You can limit the posting of an interstitial ad to a period of time in seconds after the ad is closed, during which display attempts will fail. Unlimited by default 0 seconds.  
That the interval starts only after the Interstitial `didDismissContent`.
During interval after ad closed, display attempts will fire event `didFailToPresentWithError` with `AdErrorCode.notPassedInterval`.  

```swift
interstitialAd.minInterval = interval
```

If you need to wait for a period of time after the start of the app or after showing a Rewarded Ad until next Interstitial Ad impression then call the following method:

<CodeGroup synchronize="true">
```swift
interstitialAd.restartInterval();
```

```objc
[self.interstitialAd restartInterval];
```
</CodeGroup>

You can define a different interval for each ad instance. However, the countdown will always start from the moment any ad instance is closed within the session.

## Mute Ad sounds
Indicates if the application’s audio is muted. Affects initial mute state for all ads.  
Use this method only if your application has its own volume controls.  

<CodeGroup synchronize="true">
```swift
CAS.settings.mutedAdSounds = true
```

```objc
CAS.settings.mutedAdSounds = YES;
```
</CodeGroup>

## Release ad resource
It is important to `destroy()` loaded but not displayed ads.

<CodeGroup synchronize="true">
```swift
deinit {
    appOpenAd.destroy()
}
```

```objc
- (void)dealloc {
    [self.interstitialAd destroy];
}
```
</CodeGroup>

## Samples
- [SwiftUI Interstitial Ad ViewModel](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20SwiftUI/CASSwiftUIDemoApp/InterstitialAd/InterstitialAdModel.swift)
- [Swift Interstitial Ad UIViewController](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20Swift/CASSample/InterstitialAd/InterstitialVC.swift)
- [Objective-C Interstitial Ad UIViewController](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20Objective-C/CASSample/InterstitialAd/InterstitialVC.m)

## Some best practices
#### Consider whether interstitial ads are the right type of ad for your app.
Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, like sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it's easy to present an interstitial ad without disrupting their experience. Make sure you consider at which points in your app's workflow you'll display interstitial ads and how the user is likely to respond.

#### Remember to pause the action when displaying an interstitial ad.
There are a number of different types of interstitial ads: text, image, video, and more. It's important to make sure that when your app displays an interstitial ad, it also suspends its use of some resources to allow the ad to take advantage of them. For example, when you make the call to display an interstitial ad, be sure to pause any audio output being produced by your app. You can resume playing sounds in the `didDismissContent` event handler, which will be invoked when the user has finished interacting with the ad. In addition, consider temporarily halting any intense computation tasks (such as a game loop) while the ad is being displayed. This will ensure that the user doesn't experience slow or unresponsive graphics or stuttered video.

#### Allow for adequate loading time.
Just as it's important to make sure you display interstitial ads at an appropriate time, it's also important to make sure the user doesn't have to wait for them to load. Loading the ad in advance before you intend to show can ensure that your app has a fully loaded interstitial ad at the ready when the time comes to display one.

#### Don't flood the user with ads.
While increasing the frequency of interstitial ads in your app might seem like a great way to increase revenue, it can also degrade the user experience and lower clickthrough rates. Make sure that users aren't so frequently interrupted that they're no longer able to enjoy the use of your app.
```

### Load Native Ads

Source: https://production.docs.page/docs/ios/load-native-ads

```mdx

Native ads are advertising assets seamlessly integrated into the user interface using components that are native to the platform.
They are displayed through the same views you use to construct your app's layouts, allowing for a cohesive user experience. 
Additionally, these ads can be customized to align with your app's visual design, ensuring they feel like a natural part of the content rather than intrusive advertisements.

Below is a diagram showing the ad lifecycle.
<Image zoom src="/assets/ios/Lifecycle-Native-Ad.png" alt="Diagram" height="500" />


## Load Ad
Native ads are loaded with the `CASNativeLoader` class. A `CASNativeLoaderDelegate` for handling events related to native ad content.  
In most cases, a `casID` is the same as your application package name.

<CodeGroup synchronize="true">
```swift
import CleverAdsSolutions

class MyViewController: UIViewController, CASNativeLoaderDelegate { 

    let adLoader = CASNativeLoader(casID: MyAppDelegate.casID)

    override func viewDidLoad() {
        super.viewDidLoad()
        loadNativeAds()
    }

    func loadNativeAds(){
        let loaderDelegate: CASNativeLoaderDelegate = self
        adLoader.delegate = loaderDelegate
        adLoader.adChoicesPlacement = AdChoicesPlacement.topRight // by default
        adLoader.isStartVideoMuted = true // by default
        adLoader.loadAd()
    }
    
    // MARK: - CASNativeLoaderDelegate
    
    func nativeAdDidLoadContent(_ ad: NativeAdContent) {
        receiveNativeAdContentEvents(ad)
        registerNativeAdContent(ad)  
    }

    func nativeAdDidFailToLoad(error: AdError) {
        // (Optional) Handle Ad load errors  
    }
}
```

```objc
#import <CleverAdsSolutions/CleverAdsSolutions.h>

@interface MyViewController : UIViewController <CASNativeLoaderDelegate>
@property (nonatomic, strong) CASNativeLoader *adLoader;
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadNativeAds];
}

- (void)loadNativeAds {
    self.adLoader = [[CASNativeLoader alloc] initWithCasID: @"MyAppDelegate.casID"];
    self.adLoader.delegate = self;
    self.adLoader.adChoicesPlacement = CASChoicesPlacementTopRight; // by default
    self.adLoader.isStartVideoMuted = YES; // by default
    [self.adLoader loadAd];
}

#pragma mark - CASNativeLoaderDelegate

- (void)nativeAdDidLoadContent:(CASNativeAdContent *)ad {
    [self receiveNativeAdContentEvents:ad];
    [self registerNativeAdContent:ad];
}

- (void)nativeAdDidFailToLoadWithError:(CASError *)error {
    // (Optional) Handle Ad load errors
}

// ...

@end
```
</CodeGroup>

After a call to `loadAd()`, a single callback is made to the previously defined `CASNativeLoaderDelegate` to deliver the native ad object or report an error.

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements.

The placement name should be set before loading the ads. Maximum 100 characters allowed for the placement name.

<CodeGroup synchronize="true">
```swift
adLoader.placement = "BestPlace"
```

```objc
adLoader.placement = @"BestPlace";
```
</CodeGroup>


### Autoload Ad mode
The `CASNativeLoader` does not have an autoload ad mode like other ad formats, so you need to implement error handling and ad reloading manually.

## Load multiple ads (optional)
The `load(maxNumberOfAds:)` method takes an additional parameter: the number of ads the SDK should attempt to load for the request. It's not guaranteed that the SDK will return the exact number of ads requested.

<CodeGroup synchronize="true">
```swift
adLoader.load(maxNumberOfAds: 3)
```

```objc
[self.adLoader loadWithMaxNumberOfAds:3];
```
</CodeGroup>

The `nativeAdDidLoadContent(_:)` will be called multiple times, once for each ad that is successfully loaded, up to the specified maximum number of ads.  
If the load operation fails, the `nativeAdDidFailToLoad(error:)` will be called once with the error details.

Apps requesting multiple ads should call `CASNativeLoader.isLoading` in their callback implementations to determine whether the loading process has finished.

<CodeGroup synchronize="true">
```swift
func nativeAdDidLoadContent(_ ad: NativeAdContent) {  
    receiveNativeAdContentEvents(ad)
    registerNativeAdContent(ad)
    
    if (adLoader.isAdLoading) {
        // The AdLoader is still loading ads.
        // Expect more nativeAdDidLoadContent(_:) 
        // or nativeAdDidFailToLoad(error:) callbacks.
    } else {
        // The AdLoader has finished loading ads.
    }   
} 
```

```objc
- (void)nativeAdDidLoadContent:(CASNativeAdContent *)ad {
    [self receiveNativeAdContentEvents:ad];
    [self registerNativeAdContent:ad];
    
    if (self.adLoader.isAdLoading) {
        // The AdLoader is still loading ads.
        // Expect more nativeAdDidLoadContent:
        // or nativeAdDidFailToLoadWithError: callbacks.
    } else {
        // The AdLoader has finished loading ads.
    }
}
```
</CodeGroup>

## Receive Ad events
To be notified of events related to the native ad interactions, set the delegate property of the native ad and then implement `CASNativeContentDelegate` to receive the following delegate calls:

<CodeGroup synchronize="true">
```swift
class AppController: UIViewController, CASNativeContentDelegate, CASNativeLoaderDelegate { 

    func receiveNativeAdContentEvents(_ nativeAd: NativeAdContent) {
        let adInfo: AdContentInfo = netiveAd.adInfo
        
        let nativeAdDelegate: CASNativeContentDelegate = self
        nativeAd.delegate = nativeAdDelegate
    }

    // MARK: - CASNativeContentDelegate
    
    func nativeAd(_ ad: NativeAdContent, didFailToPresentWithError error: AdError) {
        // (Optional) Handle Ad render errors. 
        // Called from CASNativeView.bindAdContent(nativeAd)  
    }

    func nativeAdDidClickContent(_ ad: NativeAdContent) {
        // (Optional) Called when the native ad is clicked by the user.  
    }
}
```

```objc
@interface AppController : UIViewController <CASNativeAdContentDelegate, CASNativeLoaderDelegate>
@end

@implementation AppController

- (void)receiveNativeAdContentEvents:(CASNativeAdContent *)nativeAd {
    CASContentInfo *adInfo = nativeAd.contentInfo;
    nativeAd.delegate = self;
}

#pragma mark - CASNativeContentDelegate

- (void)nativeAd:(CASNativeAdContent *)ad didFailToPresentWithError:(CASError *)error {
    // (Optional) Handle Ad render errors.
    // Called from [CASNativeView bindAdContent:nativeAd]
}

- (void)nativeAdDidClickContent:(CASNativeAdContent *)ad {
    // (Optional) Called when the native ad is clicked by the user.
}

@end
```
</CodeGroup>

Don't implement any custom click handlers on any views over or within the native ad view. To observe click events yourself, use the ad delegate `nativeAdDidClickContent(_:)`. Clicks on the ad view assets are handled by the SDK as long as you correctly populate and register the asset views, as discussed in the previous section.
```

### Manually configure project

Source: https://production.docs.page/docs/ios/manually-configure-project

```mdx

<Info>
We have created a script that performs all the steps below automatically for you. Learn how to invoke automatic configuration on the [Project Setup page](ios).
</Info>

## AdAttributionKit and SKAdNetwork Support
Read more on [Apple Ad Attribution page](general/apple-ad-attribution).

## App Transport Security
[App Transport Security (ATS)](https://developer.apple.com/documentation/bundleresources/information_property_list/nsapptransportsecurity) is a privacy feature introduced in iOS 9. It's enabled by default for new apps and enforces secure connections.   
To ensure your ads are not impacted by ATS, add the `NSAllowsArbitraryLoads` exception to disable ATS restrictions:

| Key | Type | Value |
|---|:---:|---|
| Information Property List | Dictionary | |
| ▼ App Transport Security Settings | Dictionary | |
| - Allow Arbitrary Loads | Boolean | YES |

Or, open plist as source code:
```xml
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
```

<Info>
Make sure that your info.plist does not contain any other exceptions besides `NSAllowsArbitraryLoads`, as this might create a conflict.
</Info>

## Link the project
To link your project with the mediation settings, you need to have a registered account and an application in the CAS system.

<Info>
If you haven't created an CAS account and registered the app yet, now's a great time to do so.  
If you just want to experiment or test the SDK, you can skip link your project.
</Info>

1. Sign In https://cleveradssolutions.com.
2. Select the Applications section on the right panel.
3. Click the plus(**+**) button and follow the instructions on the form. It may take up to 30 minutes to register the app in the CAS system.
4. After the registration completed, click the **Action** button in the row of your application

![dashboardcasapps](https://user-images.githubusercontent.com/22005013/225905839-6b494a90-a400-49d9-a070-ae930e4ff225.jpg)  


CAS uses a mediation configuration caching system to handle unexpected situations.
1. Click **Download CAS settings** button.
2. A `cas_settings[settings_id].json` file will be downloaded.  
3. Move your config file into the root of your Xcode project.
4. If prompted, select to add the config file to all targets.

<Accordion title="What do you need to know about this config file?">

- The CAS config file contains unique, but non-secret identifiers for your project.  
- The configuration file is updated frequently, so we recommend that you regularly download the latest file for each new release.
- Please do not change the name of the file. Make sure the config file name is not appended with additional characters, like `(2)`.
- The `[settings_id]` is the internal unique identifier of the resource.  
- If you have multiple CAS manager IDs in your project, you must associate each CAS ID with a registered app in the CAS console so that each app can have its own `cas_settings[settings_id].json` file.
</Accordion>

### Add Google Ads App ID 
CAS assigns a new AdMob App ID for your application to the correct operation of all features.    
<Error>  
You cannot use your own identifier and must replace it with a new one generated by CAS system.  
</Error>

You can find your Admob App ID in the CAS UI:   
1. Click the **Show AdMob App ID** button.
2. Copy the id from the form.
3. Add a `GADApplicationIdentifier` key to your app's `Info.plist` file.  
5. Insert AdMob app ID to `<string>`, as shown below.
```xml
<!-- Sample AdMob App ID: ca-app-pub-3940256099942544~1458002511 -->
<key>GADApplicationIdentifier</key>
<string>ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy</string>
```
Or, edit it in the property list editor:

| Key                        |    Type    | Value                                  |
| -------------------------- | :--------: | -------------------------------------- |
| Information Property List  | Dictionary |                                        |
| ▼ GADApplicationIdentifier |   String   | ca-app-pub-3940256099942544~1458002511 |

In a real app, replace the sample app ID with your **actual AdMob app ID**. You can use the sample ID if you're just experimenting with the SDK in a Hello World app.

Also, note that failure to add the `<meta-data>` tag exactly as shown results in a crash with the message: `Missing application ID`

## Delay app measurement

By default, the Google Mobile Ads SDK initializes app measurement and begins sending user-level event data to Google immediately when the app starts. This initialization behavior ensures you can enable AdMob user metrics without making additional code changes.

However, if your app requires user consent before these events can be sent, you can delay app measurement until CAS explicitly initialize the Google Mobile Ads SDK.

To delay app measurement, add the `GADDelayAppMeasurementInit` key with a boolean value of `YES` to your app’s `Info.plist`. You can make this change programmatically:

```xml
<key>GADDelayAppMeasurementInit</key>
<true/>
```
Or, edit it in the property list editor:

| Key | Type | Value |
|---|:---:|---|
| Information Property List | Dictionary | |
| ▼ GADDelayAppMeasurementInit | Boolean | YES |
```

### Mediated Networks

Source: https://production.docs.page/docs/ios/mediated-networks

```mdx

Advanced publishers who are familiar with ad network integrations can choose their own set of adapters. If you have any questions or need assistance, please contact your account manager.  

Feel free not to use the ready-made [Ads Solutions](ios#choose-mediated-networks), and choose which mediated ad networks you want to integrate.

The adapters are sorted alphabetically in the lists below. Every adapter already brings the CAS base framework with it, and requires no additional framework dependencies.

## The following ad sources are available for monetization to everyone

<Tabs groupId="ios-dependency-manager">
<TabItem value="spm" label="Swift Package Manager">

Add these products of the CAS package to your app target:
```
CASMediationChartboost
CASMediationDTExchange
CASMediationGoogleAds
CASMediationInMobi
CASMediationIronSource
CASMediationKidoz
CASMediationLiftoffMonetize
CASMediationMintegral
CASMediationUnityAds
```

<Info>
`CASMediationSuperAwesome` has no Swift Package product and is available through CocoaPods only.
</Info>

</TabItem>
<TabItem value="cocoapods" label="CocoaPods">

```ruby
  pod 'CASMediationChartboost'
  pod 'CASMediationDTExchange'
  pod 'CASMediationGoogleAds'
  pod 'CASMediationInMobi'
  pod 'CASMediationIronSource'
  pod 'CASMediationKidoz'
  pod 'CASMediationLiftoffMonetize'
  pod 'CASMediationMintegral'
  pod 'CASMediationSuperAwesome'
  pod 'CASMediationUnityAds'
```

</TabItem>
</Tabs>

## The following ad sources do NOT provide monetization for users under COPPA restrictions.

<Tabs groupId="ios-dependency-manager">
<TabItem value="spm" label="Swift Package Manager">

Add these products of the CAS package to your app target:
```
CASMediationAppLovin
CASMediationAudienceNetwork
CASMediationBigo
CASMediationCASExchange
CASMediationHyprMX
CASMediationMaticoo
CASMediationOgury
CASMediationPangle
CASMediationPrado
CASMediationSmaato
CASMediationStartIO
CASMediationVerve
CASMediationYangoAds
CASMediationYsoNetwork
```

</TabItem>
<TabItem value="cocoapods" label="CocoaPods">

```ruby
  pod 'CASMediationAppLovin'
  pod 'CASMediationAudienceNetwork'
  pod 'CASMediationBigo'
  pod 'CASMediationCASExchange'
  pod 'CASMediationHyprMX'
  pod 'CASMediationMaticoo'
  pod 'CASMediationOgury'
  pod 'CASMediationPangle'
  pod 'CASMediationPrado'
  pod 'CASMediationSmaato'
  pod 'CASMediationStartIO'
  pod 'CASMediationVerve'
  pod 'CASMediationYangoAds'
  pod 'CASMediationYsoNetwork'
```

</TabItem>
</Tabs>

<Info>
Read more about the adapter versions [here](https://github.com/cleveradssolutions/CAS-iOS/blob/master/Adapters/README.md).
</Info>

<Info>
- The Meta Audience Network requires [Additional implementations](ios/additional-meta-audiencenetwork-steps).
- The HyprMX is focused on the USA and Canada regions only and your apps must be approved for monetization.
</Info>

## Closed beta ad SDKs
<Warning>  
Access to the monetization of the beta ad sources is closed.  
If you would like to monetize by one of these ad sources, please contact your account manager.
</Warning>

<Tabs groupId="ios-dependency-manager">
<TabItem value="spm" label="Swift Package Manager">

```
CASMediationBidease
CASMediationBidMachine
CASMediationBlueSea
CASMediationDisplayIO
CASMediationMoloco
CASMediationMonetrix
CASMediationPubMatic
```

</TabItem>
<TabItem value="cocoapods" label="CocoaPods">

```ruby
  pod 'CASMediationBidease'
  pod 'CASMediationBidMachine'
  pod 'CASMediationBlueSea'
  pod 'CASMediationDisplayIO'
  pod 'CASMediationMoloco'
  pod 'CASMediationMonetrix'
  pod 'CASMediationPubMatic'
```

</TabItem>
</Tabs>

## Cross-promotion
Cross promotion is an app marketing strategy in which app developers promote one of their titles on another one of their titles. Cross promoting is especially effective for developers with large portfolios of games as a means to move users across titles and use the opportunity to scale each of their apps. This is most commonly used by hyper-casual publishers who have relatively low retention, and use cross promotion to keep users within their app portfolio.

<Tabs groupId="ios-dependency-manager">
<TabItem value="spm" label="Swift Package Manager">

```
CASMediationCrossPromo
```

</TabItem>
<TabItem value="cocoapods" label="CocoaPods">

```ruby
  pod 'CASMediationCrossPromo'
```

</TabItem>
</Tabs>

<Info>
Contact our account manager if you are interested in cross-promotion.
</Info>

## Apply the changes

<Tabs groupId="ios-dependency-manager">
<TabItem value="spm" label="Swift Package Manager">

Xcode resolves the package the moment you add a product. To pick up a new version later, select **File > Packages > Resolve Package Versions**.

</TabItem>
<TabItem value="cocoapods" label="CocoaPods">

After any change to `Podfile`, you need to run a terminal command to apply the changes:
```
pod update
```

</TabItem>
</Tabs>
```

### Native Ad assets

Source: https://production.docs.page/docs/ios/native-ad-assets

```mdx


| Name             | Type                        | Required    | Included                   | Description                                                                                                                                 |
| ---------------- | --------------------------- | ----------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| adChoicesView    | CASChoicesView              | Yes         | Always                     | Read below about [AdChoices overlay](ios/native-ad-assets#adchoices-overlay).                                                                                   |
| mediaView        | CASMediaView                | Yes         | Always                     | Read below about [Media Content](ios/native-ad-assets#media-content).                                                                                           |
| headlineView     | UILabel                     | Yes         | Always                     | The headline text of the native ad.                                                                                                         |
| adLabelView      | UILabel                     | If provided | Not always                 | Read below about [Ad attribution](ios/native-ad-assets#ad-attribution).                                                                                         |
| callToActionView | UIButton                    | If provided | Not always                 | Button that encourages users to take action (for example, "Visit site" or "Install"). This text may truncate after 15 characters.           |
| iconView         | UILabel                     | If provided | Always for app install ads | The small app icon or advertiser logo with square aspect ratio (1:1).                                                                       |
| bodyView         | UILabel                     | No          | Always                     | The body text of the native ad. This text may truncate after 90 characters.                                                                 |
| advertiserView   | UILabel                     | No          | Always for content ads     | Text that identifies the advertiser (for example, advertiser name, brand name, or visible URL). This text may truncate after 25 characters. |
| storeView        | UILabel                     | No          | Not always                 | The name of the store where the product or service is available.                                                                            |
| priceView        | UILabel                     | No          | Not always                 | The price of the product or service advertised.                                                                                             |
| reviewCountView  | UILabel                     | No          | Not always                 | The number of reviews the app has received.                                                                                                 |
| starRatingView   | UIView or CASStarRatingView | No          | Not always                 | Read below about [Star Rating](ios/native-ad-assets#star-rating-view).                                                                                          |

## Advertising requirements
- Native ads smaller than 32x32 points won't serve. Ads this small can be difficult to see or interact with and may adversely affect the display quality of advertiser assets.
- For native video ads, the main asset `mediaView` must be at least 120x120 points. Video ads won't serve to implementations with main asset `CASMediaView` smaller than 120 points in any dimension.
- The Ad View must be visible and non-transparent.
- At a single point in time, a loaded ad can only be served in one View. Simultaneous display of a single ad in multiple Views may result in the loss of impression.
- The app must be active (not running in the background).
- Don't edit the text content of assets.
- Don't edit the content of images.

### Media Content
You're required to use the `CASMediaView` asset instead of the `UIImageView` asset if you want to include a main image asset in the layout for your native ad.  
The `CASMediaView` is a special `UIView` designed to display the main media asset, either video or image. Can be defined in an XML layout or constructed dynamically. It should be placed within the view hierarchy of a `CASNativeView`, just like any other asset view.  The media view will be populated automatically when calling `bindAdContent()`.
- Check if the video asset is available using `nativeAd.hasVideoContent`.
- Obtain the recommended aspect ratio of the media content using `nativeAd.mediaContentAspectRatio`.

### Ad attribution
You must clearly display the text "Ad", "Advertisement", or "Sponsored" (localized appropriately). The badge is required to be a minimum of 15px height and width. Ad attribution must be displayed at the top of the ad.

### AdChoices overlay
Ad AdChoices overlay logo must be displayed at the top of the ad 
Each ad view must display an AdChoices overlay logo. Also, it's important that the AdChoices overlay be easily seen, so choose background colors and images appropriately.

#### Use AdChoices placements
An AdChoices overlay can be added by the SDK if `CASNativeView.adChoicesView` not registered. Leave space in your preferred corner of your native ad view for the automatically inserted AdChoices logo.  
Use `AdChoicesPlacement` constants to set preferred corner. 

<CodeGroup synchronize="true">
```swift
adLoader.adChoicesPlacement = AdChoicesPlacement.topRight
```

```objc
adLoader.adChoicesPlacement = CASChoicesPlacementTopRight;
```
</CodeGroup>

By default the AdChoices icon position is set to the top right.

#### Use custom AdChoices view
The AdChoices custom view feature lets you position the AdChoices icon in a custom location. This is different from AdChoices position controls, which only allows specification of one of the four corners.  
The following example demonstrates how to set a custom AdChoices view, with the AdChoices icon rendered inside the `CASChoicesView`.

<CodeGroup synchronize="true">
```swift
@IBOutlet weak var adChoicesView: CASChoicesView!
// ...
adView.adChoicesView = adChoicesView
```

```objc
@property (nonatomic, weak) IBOutlet CASChoicesView *adChoicesView;
// ...
adView.adChoicesView = self.adChoicesView;
```
</CodeGroup>

<Info>
Google Ads does not support `adView.adChoicesView`. Instead, specify the desired `AdChoicesPlacement` for the logo. Other ad sources will display their logo in your custom view.
</Info>

### Star Rating view
The rating from 0.0-5.0 that represents the average rating of the app in a store.
#### Use template view with auto populate rating value
Add `CASStarRatingView` to view hierarchy and CAS SDK populate rating value for you.

<CodeGroup synchronize="true">
```swift
@IBOutlet weak var starRatingView: CASStarRatingView!
// ...
adView.starRatingView = starRatingView
```

```objc
@property (nonatomic, weak) IBOutlet CASStarRatingView *starRatingView;
// ...
adView.starRatingView = self.starRatingView;
```
</CodeGroup>

#### Use custom view with auto populate rating value 
Implement `NativeAdStarRating` interface in your custom view.

<CodeGroup synchronize="true">
```swift
class CustomRatingView : UIView, NativeAdStarRating {
    var rating: NSNumber?
}

@IBOutlet weak var starRatingView: CustomRatingView!
// ...
adView.starRatingView = starRatingView
```

```objc
@interface CustomRatingView : UIView <CASNativeAdStarRating>
@property (nonatomic, strong) NSNumber *rating;
@end

@implementation CustomRatingView
@end

@property (nonatomic, weak) IBOutlet CustomRatingView *starRatingView;
// ...
adView.starRatingView = self.starRatingView;
```
</CodeGroup>

#### Use custom view with manual populate rating value
You need populate `nativeAd.starRating` value to custom view, for example `RatingBar` view:

<CodeGroup synchronize="true">
```swift
if let rating = nativeAd.starRating {
    customRatingView.rating = rating
}

adView.starRatingView = customRatingView
```

```objc
if (nativeAd.starRating != nil) {
    self.starRatingView.rating = nativeAd.starRating;
}

adView.starRatingView = self.starRatingView;
```
</CodeGroup>
```

### Purchase Info

Source: https://production.docs.page/docs/ios/purchase-info

```mdx

The `PurchaseInfo` class is used to report in-app purchases to CAS.AI. Along with the SDK's ad revenue tracking, this allows you to get a complete picture of a user's total value by combining ad revenue and IAP revenue in one place.

The total reported revenue is calculated as:

```
revenue = quantity * price * currency_rate
```

## Reporting a purchase

Call `CAS.reportPurchase(_:)` with a `PurchaseInfo` object as soon as you've confirmed a completed transaction. This feeds IAP revenue into CAS.AI alongside your ad revenue.

<Info>
`PurchaseInfo` is exposed to Objective-C as `CASPurchaseInfo`.
</Info>

Where you call it depends on which StoreKit version you use:
- **StoreKit 2 (Swift):** inside your `Transaction.updates` listener, right after you verify the transaction. This is typically also where you'd call `transaction.finish()`.
- **StoreKit 1 (Objective-C):** inside your `SKPaymentTransactionObserver`'s `paymentQueue:updatedTransactions:` delegate method, in the `SKPaymentTransactionStatePurchased` case. This is typically also where you'd call `finishTransaction:`.

### 1. Create `PurchaseInfo`

Build the object from the transaction's product ID, price, currency, and quantity.

<CodeGroup synchronize="true">
```swift SK2 (Swift)
// Inside your Transaction.updates listener
func listenForTransactions() -> Task<Void, Error> {
    Task.detached {
        for await result in Transaction.updates {
            guard let transaction = try? self.verify(result) else { continue }

            let purchaseInfo = PurchaseInfo(
                productID: transaction.productID,
                price: transaction.price ?? 0,
                currency: transaction.currency?.identifier,
                quantity: transaction.purchasedQuantity
            )

            // See steps 2-4 below, then call CAS.reportPurchase(purchaseInfo)

            await transaction.finish()
        }
    }
}
```

```objc SK1 (Objective-C)
// Inside your SKPaymentTransactionObserver
- (void)paymentQueue:(SKPaymentQueue *)queue
 updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        if (transaction.transactionState != SKPaymentTransactionStatePurchased) {
            continue;
        }

        CASPurchaseInfo *purchaseInfo = [[CASPurchaseInfo alloc]
            initWithProductID:transaction.payment.productIdentifier
                        price:product.price
                     currency:product.priceLocale.currencyCode
                     quantity:transaction.payment.quantity];

        // See steps 2-4 below, then call [CAS reportPurchase:purchaseInfo]

        [queue finishTransaction:transaction];
    }
}
```
</CodeGroup>

### 2. Recommended: attach validation data

Add the transaction's validation info so CAS.AI can verify the purchase server-side.

<CodeGroup synchronize="true">
```swift SK2 (Swift)
purchaseInfo.addValidation(
    transactionID: transaction.id,
    jwsRepresentation: result.jwsRepresentation
)
```

```objc SK1 (Objective-C)
NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];

[purchaseInfo addValidationWithTransactionID:transaction.transactionIdentifier
                                  receiptData:receiptData];
```
</CodeGroup>

### 3. If the product is a subscription, also call `addSubscription`

StoreKit doesn't hand you a ready-made "is this a subscription" flag on the transaction itself. That comes from your own product catalog (e.g. the `Product.ProductType` you fetched when listing products, or however you classify product IDs on your side). Check that first, then attach the subscription data:

<CodeGroup synchronize="true">
```swift SK2 (Swift)
// Determine this from your product catalog, e.g. product.type == .autoRenewable
let isSubscription: Bool = MyStore.isSubscription(transaction.productID)

if isSubscription {
    purchaseInfo.addSubscription(
        originalID: transaction.originalID,
        originalPurchaseDate: transaction.originalPurchaseDate,
        jsonRepresentation: transaction.jsonRepresentation
    )
}
```

```objc SK1 (Objective-C)
// Determine this from your product catalog
BOOL isSubscription = [MyStore isSubscriptionProductID:transaction.payment.productIdentifier];

if (isSubscription) {
    [purchaseInfo addSubscriptionFromStoreKit];
}
```
</CodeGroup>

<Info>
`addSubscriptionFromStoreKit` requires iOS 16.0+ and pulls the subscription data automatically from `Transaction.currentEntitlement`.
</Info>

### 4. Report

With the product info, validation, and (if applicable) subscription data attached, `purchaseInfo` is ready to send:

<CodeGroup synchronize="true">
```swift SK2 (Swift)
CAS.reportPurchase(purchaseInfo)
```

```objc SK1 (Objective-C)
[CAS reportPurchase:purchaseInfo];
```
</CodeGroup>

## Automatic forwarding to Tenjin
 
Purchases reported through `CAS.reportPurchase(_:)` can also be forwarded automatically to Tenjin Analytics, so you don't need a separate integration to get IAP revenue into Tenjin.
```

### Rewarded Ads

Source: https://production.docs.page/docs/ios/rewarded-ads

```mdx

Rewarded ads let you offer users in-app items, such as continued gameplay, virtual currency, or other rewards, in exchange for their engagement with ads. 
Rewarded ads boost engagement because users receive a tangible benefit for their time.

Below is a diagram showing the ad lifecycle.
<Image zoom src="/assets/ios/Lifecycle-Rewarded-Ad.png" alt="Diagram" height="500" />


## Create Ad instance
Ad instance can be initialized along with the UIViewController before `viewDidLoad`.

<CodeGroup synchronize="true">
```swift
import CleverAdsSolutions

class MyViewController: UIViewController, CASScreenContentDelegate {

    let rewardedAd = CASRewarded(casID: MyAppDelegate.casID)

```

```objc
#import <CleverAdsSolutions/CleverAdsSolutions.h>

@interface MyViewController : UIViewController <CASScreenContentDelegate>
@property (nonatomic, strong) CASRewarded *rewardedAd;
@end

@implementation MyViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        _rewardedAd = [[CASRewarded alloc] initWithCasID:MyAppDelegate.casID];
    }
    return self;
}

@end
```
</CodeGroup>

The SDK provides the capability to create and precache multiple ad instances, enabling uninterrupted sequential ad display. CAS SDK will load mediation ads in order for each created instance.

## Receive Ad events
The `CASScreenContentDelegate` handles events related to displaying your `CASInterstitial`. Callbacks are called on the main thread. Before showing ad, make sure to set `delegate`.

<CodeGroup synchronize="true">
```swift
func screenAdDidLoadContent(_ ad: any CASScreenContent) {
    // Called when the ad content has been successfully loaded.
}

func screenAd(_ ad: any CASScreenContent, didFailToLoadWithError error: AdError) {
    // Called when the ad content fails to load.
}

func screenAd(_ ad: any CASScreenContent, didFailToPresentWithError error: AdError) {
    // Called when the ad content fails to present.
}

func screenAdWillPresentContent(_ ad: any CASScreenContent) {
    // Called when the ad content is successfully shown.
}

func screenAdDidClickContent(_ ad: any CASScreenContent) {
    // Called when the ad content is clicked by the user.
}

func screenAdDidDismissContent(_ ad: any CASScreenContent) {
    // Called when the ad content is dismissed.
}
```

```objc
- (void)screenAdDidLoadContent:(id<CASScreenContent>)ad {
    // Called when the ad content has been successfully loaded.
}

- (void)screenAd:(id<CASScreenContent>)ad didFailToLoadWithError:(CASError *)error {
    // Called when the ad content fails to load.
}

- (void)screenAd:(id<CASScreenContent>)ad didFailToPresentWithError:(CASError *)error {
    // Called when the ad content fails to present.
}

- (void)screenAdWillPresentContent:(id<CASScreenContent>)ad {
    // Called when the ad content is successfully shown.
}

- (void)screenAdDidClickContent:(id<CASScreenContent>)ad {
    // Called when the ad content is clicked by the user.
}

- (void)screenAdDidDismissContent:(id<CASScreenContent>)ad {
    // Called when the ad content is dismissed.
}
```
</CodeGroup>

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](ios/impression-level-data).
- Attempting to load a new ad from the `didFailToLoadWithError` method is strongly discouraged. Limit ad load retries to avoid continuous failed ad requests in situations such as limited network connectivity.
- When an error occurs during ad impression, executed the `didFailToPresentWithError` only.  In this case the `didDismissContent` will not be executed, since the impression is not considered successful.
</Info>

## Load Ad
The next step is to fill out the `loadAd()` method and handle the ad load callbacks.

<CodeGroup synchronize="true">
```swift
override func viewDidLoad() {
    super.viewDidLoad()

    let screenContentDelegate: CASScreenContentDelegate = self
    rewardedAd.delegate = screenContentDelegate
    rewardedAd.loadAd();
}
```

```objc
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.rewardedAd.delegate = self;
    [self.rewardedAd loadAd];
}
```
</CodeGroup>

You can use ad load calls to build up a cache of preloaded ads before you intend to show them, so that ads can be shown with zero latency when needed. Since ads expire after an hour, you should clear this cache and reload with new ads every hour.

### Autoload mode
If enabled, the ad will automatically load new content when the current ad is dismissed or completed. Additionally, it will automatically retry loading the ad if an error occurs during the loading process.  

<CodeGroup synchronize="true">
```swift
override func viewDidLoad() {
    super.viewDidLoad()

    let screenContentDelegate: CASScreenContentDelegate = self
    rewardedAd.delegate = screenContentDelegate
    rewardedAd.isAutoloadEnabled = true
}
```

```objc
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.rewardedAd.delegate = self;
    self.rewardedAd.isAutoloadEnabled = YES;
}
```
</CodeGroup>

By default autoload disabled.

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements.

The placement name should be set before showing the ads. Maximum 100 characters allowed for the placement name.

<CodeGroup synchronize="true">
```swift
rewardedAd.placement = "BestPlace"
```

```objc
rewardedAd.placement = @"BestPlace";
```
</CodeGroup>

## Show Ad
When you present a rewarded ad, you will use an `userDidEarnRewardHandler` to handle reward  for the user.

<CodeGroup synchronize="true">
```swift
rewardedAd.present(from: self, userDidEarnRewardHandler: { (info: AdContentInfo) in
    // Called when a user earns a reward from the ad.
    // TODO: Reward the user
})
```

```objc
[self.rewardedAd presentFromViewController:self userDidEarnRewardHandler:^(CASContentInfo * _Nonnull info) {
    // Called when a user earns a reward from the ad.
    // TODO: Reward the user
}];
```
</CodeGroup>

The `UIViewController` parameter is an optional. The SDK uses the app’s main window to look up view controllers automatically when one is not provided.

Starting with CAS SDK version 4.3.0, all ads functions can be safely called from any thread.

### Checking Ad Availability
Use `isAdLoaded` to check whether an ad is currently loaded.

<CodeGroup synchronize="true">
```swift
if rewardedAd.isAdLoaded {
    // ...
}
```

```objc
if (rewardedAd.isAdLoaded) {
    // ...
}
```
</CodeGroup>

Even if `isAdLoaded` returns `true`, it does not guarantee that the ad will be shown successfully — various issues may still prevent it from being displayed. We strongly recommend handling potential display failures via `screenAd(_:didFailToPresentWithError:)` delegate to ensure a smoother user experience.

By relying on these delegate, you ensure that your application can react appropriately to real-time conditions, rather than making assumptions based on ad load state at a single point in time.

## Extra fill Interstitial Ad
Controls whether interstitial ads are shown as a fallback when a rewarded video ad has no available fill. Interstitial ads do not require the user to watch the entire ad to completion. However, the `userDidEarnRewardHandler` will still be triggered as if the user completed the rewarded video.
This option is enabled by default. You can disable extra fill by following line:

<CodeGroup synchronize="true">
```swift
rewardedAd.isExtraFillInterstitialAdEnabled = false
```

```objc
rewardedAd.isExtraFillInterstitialAdEnabled = NO;
```
</CodeGroup>

## Mute Ad sounds
Indicates if the application’s audio is muted. Affects initial mute state for all ads.  
Use this method only if your application has its own volume controls.  

<CodeGroup synchronize="true">
```swift
CAS.settings.mutedAdSounds = true
```

```objc
CAS.settings.mutedAdSounds = YES;
```
</CodeGroup>

## Release ad resource
It is important to `destroy()` loaded but not displayed ads.

<CodeGroup synchronize="true">
```swift
deinit {  
    rewardedAd.destroy();
}
```

```objc
- (void)dealloc {
    [self.rewardedAd destroy];
}
```
</CodeGroup>

## Samples
- [SwiftUI Rewarded Ad ViewModel](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20SwiftUI/CASSwiftUIDemoApp/RewardedAd/RewardedAdModel.swift)
- [Swift Rewarded Ad UIViewController](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20Swift/CASSample/RewardedAd/RewardedVC.swift)
- [Objective-C Rewarded Ad UIViewController](https://github.com/cleveradssolutions/CAS-iOS/blob/master/DemoApp%20Objective-C/CASSample/RewardedAd/RewardedVC.m)
```

### Targeting options

Source: https://production.docs.page/docs/ios/targeting-options

```mdx

You can now easily tailor the way you serve your ads to fit a specific audience!  
You’ll need to inform our servers of the users’ details so the SDK will know to serve ads according
to the segment the user belongs to.

### User ID
The userID is a unique identifier supplied by your application and must be static for each user across sessions. 

<CodeGroup synchronize="true">
```swift
CAS.getTargetingOptions().setUserID("user-hash-code");
```

```objc
[[CAS targetingOptions] setUserID:@"user-hash-code"];
```
</CodeGroup>

<Warning>  
Your userID should not contain any personally identifiable information such as  an email address, screen name, IDFV (identifier for vendor) or IDFA (Apple’s Advertising Identifier).
</Warning>

## User Age
Set user age. Limitation: 1-99. By default 0 is 'unknown'.

<CodeGroup synchronize="true">
```swift
CAS.targetingOptions.age = 12
```

```objc
[CAS targetingOptions].age = 12;
```
</CodeGroup>

## User Gender
Set user gender.

<CodeGroup synchronize="true">
```swift
CAS.targetingOptions.gender = Gender.male
```

```objc
[CAS targetingOptions].gender = CASGenderMale;
```
</CodeGroup>

## User Location
Set the user's current location. Location data is not used to CAS; however, it may be used by third party ad networks.

<CodeGroup synchronize="true">
```swift
CAS.targetingOptions.setLocation(latitude: userLatitude, longitude: userLongitude)
```

```objc
[[CAS targetingOptions] setLocationWithLatitude:userLatitude longitude:userLongitude];
```
</CodeGroup>

<Warning>  
Do not use Location just for advertising. Your app should have a valid use case for it as well.
</Warning>

### User Location auto collection
Collect from the device the latitude and longitude coordinated truncated to the hundredths decimal place. 
- Collect only if your application already has the relevant end-user permissions.  
* Does not collect if the target audience is children.   
* Disabled by default.

<CodeGroup synchronize="true">
```swift
CAS.targetingOptions.locationCollectionEnabled = true
```

```objc
[CAS targetingOptions].locationCollectionEnabled = YES;
```
</CodeGroup>

## App Keywords
Set a list of keywords, interests, or intents related to your application. Words or phrases describe
the current activity of the user for targeting purposes.

<CodeGroup synchronize="true">
```swift
CAS.targetingOptions.keywords = keywords
```

```objc
[CAS targetingOptions].keywords = keywords;
```
</CodeGroup>

## App Content URL
Set the content URL for a website whose content matches the app's primary content. This website content is used for targeting and brand safety purposes. Limitation: max URL length 512.

<CodeGroup synchronize="true">
```swift
CAS.targetingOptions.contentUrl = contentUrl
```

```objc
[CAS targetingOptions].contentUrl = contentUrl;
```
</CodeGroup>
```

### User Consent Flow

Source: https://production.docs.page/docs/ios/user-consent-flow

```mdx


<Info>
It is optional to use the CMP flow included with the CAS SDK. If you integrate your own CMP flow, make sure that flow completes before you initialize the CAS SDK.
</Info>

<Info>
If you implement a CMP that is compliant with IAB TCF v2 ([Transparency & Consent Framework](https://iabeurope.eu/tcf-2-0/)) for your user consent flow, the CAS SDK supports sending the TCF v2 consent to networks. In this case, the CAS Consent Flow will not be shown to the user.
</Info>

In order for CAS and our ad providers to deliver ads that are more relevant to your users, as a mobile app publisher, you need to collect explicit user consent for use of personal data in the regions covered by GDPR, CCPA, LGPD, PIPEDA.


### 1. Opt-in consent for the collection and use of personal data in the regions covered by GDPR, CCPA, LGPD, PIPEDA.
Any businesses established are required to comply with GDPR in Europe, CCPA in California, LGPD in Brazil, PIPEDA in Canada or risk facing heavy fines.

Keep in mind that it’s best to contact qualified legal professionals, if you haven’t done so already, to get more information and be well-prepared for compliance.  

Read more about:
- GDPR - [General Data Protection Regulation](https://gdpr-info.eu)
- CCPA - [The California Consumer Privacy Act](https://theccpa.org)
- LGPD - [General Personal Data Protection Act](https://lgpd-brazil.info)
- PIPEDA - [The Personal Information Protection and Electronic Documents Act](https://www.priv.gc.ca/en/privacy-topics/privacy-laws-in-canada/the-personal-information-protection-and-electronic-documents-act-pipeda/)

<Image height="400" alt="image" src="/assets/User-Consent-Flow-1.png" />

#### Users will not see the Consent dialog if at least one of following is true
- Users located in regions that are not covered by information protection
- Users who are subject to COPPA restrictions.

### 2. Asking user permission to track them or access their device’s advertising identifier
With iOS 14.5 and later, you need to receive the user’s permission through the `AppTrackingTransparency` framework in order to track them or access their device’s advertising identifier.  Read more about Asking Permission to Track and AppTrackingTransparency Framework on [Apple developer page](https://developer.apple.com/app-store/user-privacy-and-data-use/)

<Warning>  
If an app does not present this request, the IDFA will automatically be zeroed out, which may lead to a significant loss in ad revenue.
</Warning>

#### Users will not see the ATT request if at least one of the following is true
- Users using iOS versions below 14.5
- Users who have indicated that they do not allow apps to ask to track them, by setting *Settings > Privacy, Allow Apps to Request to Track*
- Users with child accounts, or who are under age 18, who are signed in via their Apple ID
- Users who have already answered so far
- The app does not have a usage tracking description in **Info.plist** under `NSUserTrackingUsageDescription` key


## Automatic consent flow
The automatic consent flow is enabled by default and described on the [CAS initialization page](ios/initialize-cas).

## Manual consent flow
Call `presentIfRequired()` on the `CASConsentFlow` class. If the consent is required, the SDK loads a form and immediately presents it . 
The `withCompletionHandler` is called after the form is dismissed. If consent is not required, the `withCompletionHandler` is called immediately.

<CodeGroup synchronize="true">
```swift
CASConsentFlow()
    .withCompletionHandler { status in
         if status == CASConsentFlowStatus.obtained {
            // User consent obtained.
        }
     }
    .withViewControllerToPresent(controller)
    .presentIfRequired()
```

```objc
CASConsentFlow *flow = [[CASConsentFlow alloc] init];
flow.viewControllerToPresent = self;
flow.completionHandler = ^(CASConsentFlowStatus status) {
    if (status == CASConsentFlowStatusObtained) {
        // User consent obtained.
    }
};

[flow presentIfRequired];
```
</CodeGroup>

<Warning>  
The `present()` and `presentIfRequired()` methods must be called from the main (UI) thread.
</Warning>

| ConsentFlow.Status | Description                                                        |
| ------------------ | ------------------------------------------------------------------ |
| obtained           | User consent obtained. Personalized vs non-personalized undefined. |
| notRequired        | User consent not required.                                         |
| unavailable        | User consent unavailable.                                          |
| internalError      | There was an internal error.                                       |
| networkError       | There was an error loading data from the network                   |
| flowStillShowing   | There was an error with another form is still being displayed      |

<Warning>  
The cache consent status on your app or a previously saved consent string, could lead to a [TCF 3.3](https://support.google.com/admanager/answer/9999955) error if consent is expired.
</Warning>

## Privacy options button
Some consent forms require the user to modify their consent at any time. Adhere to the following steps to implement a privacy options button if required.
1. Implement a UI element, such as a button in your app's settings page, that can trigger a privacy options form.
2. When a user interacts with your UI element, call `present()` to show the form so the user can update their privacy options at any time.

<CodeGroup synchronize="true">
```swift
func showPrivacyOptionsForm() {
    CASConsentFlow()
        .withCompletionHandler { status in
             if status == CASConsentFlowStatus.obtained {
                // User consent obtained.
            }
         }
        .withViewControllerToPresent(controller)
        .present()
}
```
```objc
- (void)showPrivacyOptionsForm {
    CASConsentFlow *flow = [[CASConsentFlow alloc] init];
    flow.viewControllerToPresent = self;
    flow.completionHandler = ^(CASConsentFlowStatus status) {
        if (status == CASConsentFlowStatusObtained) {
            // User consent obtained.
        }
    };
    [flow present];
}
```
</CodeGroup>

## Debug geography
The SDK provides a way to test your app's behavior as though the device was located in the EEA or UK using the `WithDebugGeography` option. 
<CodeGroup synchronize="true">
```swift
CASConsentFlow()
    .withDebugGeography(ConsentFlow.DebugGeography.EEA)
#if DEBUG
    .withForceTesting(true)
#endif
    .presentIfRequired();
```

```objc
CASConsentFlow *flow = [[CASConsentFlow alloc] init];
flow.viewControllerToPresent = self;
flow.completionHandler = ^(CASConsentFlowStatus status) {
    NSLog(@"Consent Flow finished: %ld", (long)status);
};
    
flow.debugGeography = CASUserDebugGeographyEEA;

#ifdef DEBUG
    flow.forceTesting = YES;
#endif
    [flow presentIfRequired];
```
</CodeGroup>

<Info>
Note that debug geography only work if:
- Active test device defined in `CAS.settings.setTestDevice(ids:)`.
- `withForceTesting` value is true.
</Info>

## Meta Audience Network Data Processing Options for Users in California
The CAS does not support your handling of CCPA opt-out values for Meta Audience Network, you must work directly with the network to  purposes of your obligations for CCPA compliance.  

To learn how to implement Meta Audience Network’s “Limited Data Use” flag, read the [Additional Meta AudienceNetwork steps](ios/additional-meta-audiencenetwork-steps).

## Custom Consent Logic
The following instructions apply if you are using your own or a third-party party consent mechanism. 

<Error>  
If you access Google demand through CAS, it’s critical that you review the [Google CMP requirements](https://support.google.com/adsense/answer/13554116) before you start the integration process.
</Error>

<Warning>  
You must set the privacy options before creating the CAS Manager to disable the automatic CAS consent flow and advertising SDKs are initialized respecting the user's consent.
</Warning>

## Request App Tracking Transparency framework
To present the authorization request, call `requestTrackingAuthorizationWithCompletionHandler:`. We recommend waiting for the completion callback prior to initialize ads, so that if the user grants the App Tracking Transparency permission, the CAS mediation can use the IDFA in ad requests.

<CodeGroup synchronize="true">
```swift
import AppTrackingTransparency

func requestIDFA() {
    ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
        // Tracking authorization completed. 
        // Start initialize CAS SDK here.
    })
}
```

```objc
#import <AppTrackingTransparency/AppTrackingTransparency.h>

- (void)requestIDFA {
    [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
        // Tracking authorization completed.
        // Initialize CAS SDK here.
    }];
}

```
</CodeGroup>

For a better user experience, we recommend adding a **Pre permission pop-up** preceding the call to `ATTrackingManager.requestTrackingAuthorization` to clarify the permission and data usage to users.  

### Consent in GDPR and Other regions
CAS shares these set consent values via adapters to supported mediation partners.  

If the user consents to interest-based advertising, set the user consent `accepted` flag:

<CodeGroup synchronize="true">
    ```swift
    CAS.settings.userConsent = CASConsentStatus.accepted
    ```

    ```objc
    CAS.settings.userConsent = CASConsentStatusAccepted;
    ```
</CodeGroup>

If the user does NOT consent to interest-based advertising, set the user consent `denied` flag:

<CodeGroup synchronize="true">
    ```swift
    CAS.settings.userConsent = CASConsentStatus.denied
    ```

    ```objc
    CAS.settings.userConsent = CASConsentStatusDenied;
    ```
</CodeGroup>

Once you set the consent value, CAS will continue to respect that value for the lifetime of your application or until the user consents to interest-based advertising.

### Multi-State Consumer privacy laws
California and Virginia laws may require you to display a “Do Not Sell or Share My Personal Information” link or provide other options to users located in those states to opt out of interest-based advertising. You must set a flag that indicates whether users in those states opt out of interest-based advertising or the sale or share of personal information for interest-based advertising.

If a user does NOT opt out of interest-based advertising, set the `optInSale` flag: 

<CodeGroup synchronize="true">
    ```swift
    CAS.settings.userCCPAStatus = CASCCPAStatus.optInSale
    ```

    ```objc
    CAS.settings.userCCPAStatus = CASCCPAStatusOptInSale;
    ```
</CodeGroup>

If a user does opt out of interest-based advertising, set the `optOutSale` flag:

<CodeGroup synchronize="true">
    ```swift
    CAS.settings.userCCPAStatus = CASCCPAStatus.optOutSale
    ```

    ```objc
    CAS.settings.userCCPAStatus = CASCCPAStatusOptOutSale;
    ```
</CodeGroup>

You do not need to set this flag for users who are outside California. If you do set this flag for such users, this will not impact how ads are served to them.
```

### Ad errors

Source: https://production.docs.page/docs/kmp/ad-errors

```mdx

In cases where an ad fails to load or show, a callback is invoked with a `CASError` object.

`CASError` is commonly used in ad-related callbacks such as `onAdFailedToLoad`, `onAdFailedToShow`,
`onBannerAdFailed` and `onNativeAdFailedToLoad`.

Use `CASError.code` to retrieve the error code.
Use `CASError.message` to get a human-readable error description.

```kotlin
override fun onAdFailedToLoad(format: CASAdFormat, error: CASError) {
    println("Ad of $format failed with code ${error.code}: ${error.message}")
}
```

See the table below for all available error codes.

| Code | Description                                                                                                                                                                                            |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 0    | Indicates an internal error occurred.                                                                                                                                                                  |
| 1    | Indicates that ads are not ready to be shown. Ensure to call the appropriate ad loading method or use automatic load mode. If using automatic load mode, wait a little longer for ads to be ready.     |
| 2    | Indicates that the device is rejected for services. Services may not be available for some devices that do not meet the requirements. For example, the country or version of the OS.                   |
| 3    | Indicates that no ads are available to be served. If ads are visible in test ads mode, your implementation is correct, and ads will be served once live.                                               |
| 6    | Indicates that the ad creative has reached its daily cap for the user. This is typically relevant for cross-promotion ads only.                                                                        |
| 7    | Indicates that the CAS SDK is not initialized. Ensure to add CAS initialization code.                                                                                                                  |
| 8    | Indicates a timeout error occurred because the advertising source did not respond in time. The system will continue waiting for a response, which may delay ad loading or cause a loading error.       |
| 9    | Indicates that there is no internet connection available, which prevents ads from loading.                                                                                                             |
| 10   | Indicates that there is a configuration error in one of the mediation ad sources. Report this error to your support manager for further assistance.                                                    |
| 11   | Indicates that the interval between impressions of interstitial ads has not yet passed. This error may also occur if a trial ad-free interval has been defined and has not yet passed since app start. |
| 12   | Indicates that another fullscreen ad is currently being displayed, preventing new ads from showing. Review your ad display logic to avoid duplicate impressions.                                       |
| 13   | Indicates that ads cannot be shown because the application is not currently in the foreground.                                                                                                         |

<Info>
`CASError` is a `data class`, so it can be compared, copied and logged directly. The error codes are stable
across platforms, which means shared code can branch on `error.code` without platform checks.
</Info>
```

### Additional Meta AudienceNetwork steps

Source: https://production.docs.page/docs/kmp/additional-meta-audiencenetwork-steps

```mdx

## Data Processing Options for US Users
Meta Audience Network Data Processing Options for US Users Limited Data Use is a data processing option that gives you more control over how your data is used in Meta’s systems and better supports your compliance efforts with various US state privacy regulations. To utilize this feature, you must proactively enable Limited Data Use.
Visit [Meta’s developer documentation](https://developers.facebook.com/docs/marketing-apis/data-processing-options) for details.

If you do not want to enable Limited Data Use (LDU) mode, pass an empty string as a value of mediation extras with key `FB_dp` in the initialize method:
```kotlin
CASMobileAds.initialize(
    context = context,
    casId = casId,
    mediationExtras = mapOf("FB_dp" to ""), // [!code highlight]
)
```
To enable LDU for users and specify user geography, set `"LDU"` in `mediationExtras`:
```kotlin
CASMobileAds.initialize(
    context = context,
    casId = casId,
    mediationExtras = mapOf("FB_dp" to "LDU"), // [!code highlight]
)
```

<Info>
The Meta Audience Network adapter is added per platform: `audienceNetwork = true` in the `cas { }` block on
Android, and the `CASMediationAudienceNetwork` library product of the CAS Swift Package on iOS.
</Info>
```

### App Open Ads

Source: https://production.docs.page/docs/kmp/app-open-ads

```mdx

App open ads are full-screen ads shown when the user opens or returns to your app.
They are designed to capture attention at a moment when the user expects a short wait, such as a loading screen.

App Open Ad management is handled through the `CASAppOpenAd` class from `commonMain`.
The ad is presented by the native CAS.AI SDK on top of all app content, so it is not part of the Compose tree.

<Image zoom src="/assets/Lifecycle-Screen-Ad.png" alt="Diagram" height="500" />

## Create Ad instance
```kotlin
import com.cleveradssolutions.plugin.kmp.CASAdContentInfo
import com.cleveradssolutions.plugin.kmp.CASAdFormat
import com.cleveradssolutions.plugin.kmp.CASAppOpenAd
import com.cleveradssolutions.plugin.kmp.CASError
import com.cleveradssolutions.plugin.kmp.CASMobileAds
import com.cleveradssolutions.plugin.kmp.CASScreenAdContentCallback

val appOpenAd = CASAppOpenAd(
    casId = "APP CAS ID",
    autoLoad = true,
    autoShow = true,
    callback = object : CASScreenAdContentCallback {
        override fun onAdLoaded(ad: CASAdContentInfo) {
            println("App open ad loaded")
        }

        override fun onAdFailedToLoad(format: CASAdFormat, error: CASError) {
            println("App open ad failed to load: ${error.message}")
        }
    },
)
```

<Info>
App open ads are most useful with both `autoLoad` and `autoShow` enabled: the SDK keeps an ad ready and
presents it when the user returns to the app, without any additional code in your app.
</Info>

## Auto Show Ad mode
With `autoShow` enabled, the SDK displays the loaded ad as soon as the user returns to the app. Note that the ad
must be ready for display at that moment, otherwise nothing is shown and loading continues in the background.

```kotlin
appOpenAd.isAutoShowEnabled = true // [!code highlight]
```

Disabled by default.

<Warning>
Do not show an app open ad on the very first launch before your app is ready to be used, and do not show it on
top of another full screen ad. Both lead to a poor user experience and may violate store policies.
</Warning>

## Show Ad manually
If you prefer to control the moment of display, keep `autoShow` disabled and call `show()` yourself, for
example once your splash screen has finished loading.

```kotlin
appOpenAd.show()
```

If the ad is not ready at that moment, the `onAdFailedToShow` callback is triggered with a reason provided in the `CASError`.

You have the option to check `isLoaded` if it's required by your app's logic.
```kotlin
val isAdLoaded: Boolean = appOpenAd.isLoaded
```

## Ad content callbacks
`CASAppOpenAd` uses the same `CASScreenAdContentCallback` as the other full screen formats. Every method has a
default empty implementation, so override only the ones you need.

```kotlin
object : CASScreenAdContentCallback {
    override fun onAdLoaded(ad: CASAdContentInfo) {}
    override fun onAdFailedToLoad(format: CASAdFormat, error: CASError) {}
    override fun onAdFailedToShow(format: CASAdFormat, error: CASError) {}
    override fun onAdShowed(ad: CASAdContentInfo) {}
    override fun onAdClicked(ad: CASAdContentInfo) {}
    override fun onAdDismissed(ad: CASAdContentInfo) {}
}
```

Impressions are reported through a separate callback:
```kotlin
appOpenAd.impressionCallback = CASAdImpressionCallback { ad ->
    println("Impression from ${ad.sourceName} with revenue ${ad.revenue}")
}
```

<Info>
Read more about the `CASAdContentInfo` structure in [Impression Level Data](kmp/impression-level-data).
</Info>

## Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.

```kotlin
appOpenAd.placement = "ColdStart" // [!code highlight]
```

## Manual reload Ad
When you want to manually control ad loading, use `load()` on the created ad instance to retry loading with the same configuration.
```kotlin
appOpenAd.load()
```

Autoload can also be switched at runtime:
```kotlin
appOpenAd.isAutoLoadEnabled = false
```

## Release ad resource
Be sure to release ad resources if you’re no longer going to use the ad instance.
```kotlin
appOpenAd.destroy() // [!code highlight]
```

Because app open ads follow the application lifecycle rather than a single screen, it usually makes sense to keep
one instance in a shared object for the whole app session instead of creating one per screen.

## Reset the interstitial interval
Showing an app open ad does not reset the [minimum interval](kmp/interstitial-ads#minimum-interval-between-impressions)
of your interstitial ads. If you want the interval to start counting from the app open impression, call
`restartInterval()` on your interstitial instance from `onAdDismissed`:

```kotlin
override fun onAdDismissed(ad: CASAdContentInfo) {
    interstitialAd.restartInterval()
}
```

## Complete example
- [App open ad example](https://github.com/cleveradssolutions/CAS-KMP/blob/main/cas-demo-app/src/commonMain/kotlin/com/cleveradssolutions/kmp/demo/screens/AppOpenExampleScreen.kt)
```

### Banner Ads

Source: https://production.docs.page/docs/kmp/banner-ads

```mdx

Banner ads occupy a spot within an app's layout, either at the top or bottom of the device screen.
They stay on screen while users interact with the app, and can refresh automatically after a period of time.

Banner ads consist of two parts:
- `CASBannerAdContent` loads and owns the ad. It lives in `commonMain` and is independent of the UI.
- The `CASBannerAd` composable displays an already created content instance in your Compose layout.

This split lets you create the content once, keep it across navigation, and place it wherever the layout needs it.

<Image zoom src="/assets/Lifecycle-Banner-Ad.png" alt="Diagram" height="500" />

## Create Ad content
```kotlin
import com.cleveradssolutions.plugin.kmp.CASAdContentInfo
import com.cleveradssolutions.plugin.kmp.CASBannerAdContent
import com.cleveradssolutions.plugin.kmp.CASBannerAdContentCallback
import com.cleveradssolutions.plugin.kmp.CASBannerSize
import com.cleveradssolutions.plugin.kmp.CASError
import com.cleveradssolutions.plugin.kmp.CASMobileAds

val bannerContent = CASBannerAdContent(
    casId = "APP CAS ID",
    size = CASBannerSize.BANNER,
    autoLoad = true,
    refreshInterval = 30,
    callback = object : CASBannerAdContentCallback {
        override fun onBannerAdLoaded(info: CASAdContentInfo) {
            println("Banner ad loaded")
        }

        override fun onBannerAdFailed(error: CASError) {
            println("Banner ad failed: ${error.message}")
        }
    },
)
```

<Warning>
`CASBannerAdContent` must be created and used on the main thread.
</Warning>

## Display the banner
Pass the content instance to the `CASBannerAd` composable. Until the ad is loaded, the composable does not
show any visible content, so it is safe to place it in the layout from the start.

```kotlin
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import com.cleveradssolutions.plugin.kmp.composable.CASBannerAd

@Composable
fun BannerScreen() {
    val bannerContent = remember {
        CASBannerAdContent(
            casId = "APP CAS ID",
            size = CASBannerSize.BANNER,
        )
    }

    DisposableEffect(bannerContent) {
        onDispose { bannerContent.destroy() } // [!code highlight]
    }

    CASBannerAd(
        adContent = bannerContent,
        modifier = Modifier.fillMaxWidth(),
    )
}
```

The same content instance can be shown by only one `CASBannerAd` at a time. To display banners on several
screens at once, create one content instance per screen.

## Banner sizes
`CASBannerSize` provides the standard sizes and the adaptive factory functions. Each size exposes its
`width` and `height` in dp.

<AccordionGroup>
<Accordion defaultOpen title="Standard sizes">

```kotlin
CASBannerSize.BANNER            // 320 x 50 dp
CASBannerSize.LEADERBOARD       // 728 x 90 dp
CASBannerSize.MEDIUM_RECTANGLE  // 300 x 250 dp
```

</Accordion>

<Accordion title="Smart banner">

Typically, smart banners on phones have a `BANNER` size. On tablets they usually have a `LEADERBOARD` size.

```kotlin
val size = CASBannerSize.getSmartBanner()
```

</Accordion>

<Accordion title="Adaptive banner">

Creates an adaptive banner size with a maximum width in dp for the current screen orientation.
Adaptive banners use fixed aspect ratios instead of fixed heights.

```kotlin
val size = CASBannerSize.getAdaptiveBanner(maxWidthDP = 360)
```

- The height of adaptive banners cannot be less than 50 dp and more than 250 dp.
- The width of adaptive banners cannot be less than 300 dp.

To use the full available width, read it from the layout:
```kotlin
BoxWithConstraints {
    val size = remember(maxWidth) {
        CASBannerSize.getAdaptiveBanner(maxWidthDP = maxWidth.value.toInt())
    }
    // Create the content with this size
}
```

</Accordion>

<Accordion title="Inline adaptive banner">

Inline adaptive banners are larger and taller than anchored adaptive banners. They are of variable height and
can be as tall as the device screen.

```kotlin
val size = CASBannerSize.getInlineBanner(width = 360, maxHeight = 200)
```

- The height of adaptive banners cannot be less than 32 dp.
- You must know the width of the view that the ad will be placed in, taking into account the device width and any applicable safe areas.
- The inline adaptive banner sizes are designed to work best when using the full available width.

</Accordion>

<Accordion title="MREC">

The Medium Rectangle size is the same `MEDIUM_RECTANGLE` constant, usually placed inside scrollable content
rather than anchored to an edge.

```kotlin
val mrecContent = CASBannerAdContent(
    casId = "APP CAS ID",
    size = CASBannerSize.MEDIUM_RECTANGLE,
)
```

</Accordion>
</AccordionGroup>

## Refresh interval
The number of seconds an ad is displayed before a new ad is shown. Set `0` to disable automatic refresh.

```kotlin
val bannerContent = CASBannerAdContent(
    casId = "APP CAS ID",
    size = CASBannerSize.BANNER,
    refreshInterval = 30, // [!code highlight]
)
```

The default is 30 seconds. Values that are too small can be rejected by mediated networks.

## Ad content callbacks
Every method of `CASBannerAdContentCallback` has a default empty implementation, so override only the ones you need.
All callbacks are invoked on the main thread.

```kotlin
object : CASBannerAdContentCallback {
    override fun onBannerAdLoaded(info: CASAdContentInfo) {
        // Invoked when the ad is loaded and ready to present.
    }

    override fun onBannerAdFailed(error: CASError) {
        // Invoked when an error occurred with the ad.
    }

    override fun onBannerAdClicked(info: CASAdContentInfo) {
        // Invoked when a user clicks the ad.
    }

    override fun onBannerAdImpression(info: CASAdContentInfo) {
        // Invoked when an ad impression is recorded.
    }
}
```

An impression callback can also be assigned separately:
```kotlin
bannerContent.impressionCallback = CASAdImpressionCallback { ad ->
    println("Impression from ${ad.sourceName} with revenue ${ad.revenue}")
}
```

<Info>
Read more about the `CASAdContentInfo` structure in [Impression Level Data](kmp/impression-level-data).
</Info>

## Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.

```kotlin
val bannerContent = CASBannerAdContent(
    casId = "APP CAS ID",
    size = CASBannerSize.BANNER,
    placement = "MainScreenBottom", // [!code highlight]
)
```

## Manual reload Ad
With `autoLoad = false`, load the banner yourself before presenting it. Calling `load()` on an already loaded
banner reloads the content and skips the pending impression.

```kotlin
bannerContent.load()
```

You have the option to check `isLoaded` if it's required by your app's logic.
```kotlin
val isAdLoaded: Boolean = bannerContent.isLoaded
```

## Release ad resource
Destroy the content when the banner is no longer needed. The ad stops refreshing and releases its resources.

```kotlin
bannerContent.destroy()
```

## Some best practices
#### Place the banner outside of scrollable content when it should stay visible.
Anchored banners belong at the top or the bottom of the screen, outside the scrolling area, so they remain
visible while the user interacts with your content.

#### Do not stack banners.
Only one banner should be visible in the same place at the same time. Several overlapping banners reduce
viewability and can violate network policies.

#### Reserve the space in advance.
Create the content and place `CASBannerAd` in the layout before the ad arrives, so your UI does not shift when
the banner appears.

## Complete example
- [Banner ad example](https://github.com/cleveradssolutions/CAS-KMP/blob/main/cas-demo-app/src/commonMain/kotlin/com/cleveradssolutions/kmp/demo/screens/BannerExampleScreens.kt)
- [Adaptive banner example](https://github.com/cleveradssolutions/CAS-KMP/blob/main/cas-demo-app/src/commonMain/kotlin/com/cleveradssolutions/kmp/demo/screens/AdaptiveBannerExampleScreen.kt)
- [MREC example](https://github.com/cleveradssolutions/CAS-KMP/blob/main/cas-demo-app/src/commonMain/kotlin/com/cleveradssolutions/kmp/demo/screens/MRecExampleScreen.kt)
```

### Enabling test ads

Source: https://production.docs.page/docs/kmp/enabling-test-ads

```mdx

It's important to enable test ads during development so that you can click on them without charging CAS advertisers.

<Error>
We strongly suggest that you enable test ads mode when you validate the integration. If you click on too many ads without being in test mode, you risk your account being flagged for invalid activity.
</Error>

There are two ways to get test ads:
- [Enable test ad mode](kmp/enabling-test-ads#enable-test-ad-mode) for all devices.
- [Set device ids to test ad](kmp/enabling-test-ads#enable-test-devices).

Ads with Test Ads mode are safe to click. Requests, impressions, and clicks on test ads will not show up in your account's reports.
Test full-screen ads display details of the CAS integration and tips for solving errors. Go to the Mediation Adapters section to make sure that the advertising networks you want are integrated correctly.

<Image height="500" alt="image" src="/assets/Enabling-test-ads-1.jpg" />
<Image height="500" alt="image" src="/assets/Enabling-test-ads-2.jpg" />

## Enable Debug log mode
The enabled Debug Mode will display a lot of useful information for debugging about the states of the SDK with log tag `CAS`.
Disabled by default. Disabling Debug Mode may improve application performance.
```kotlin
CASMobileAds.debugLoggingEnabled = true
```

On Android the output goes to Logcat, on iOS to the Xcode console.

<Info>
If you have discovered a problem in the work of the SDK, please provide us with a description of the problem along with the full log of your device.
</Info>

## Enable test ad mode
The quickest way to enable testing is to use test ad mode. Test ad mode is not associated with your CAS account, so there's no risk of your account generating invalid traffic when using it.

The easiest way to load test ads is to use the demo CAS ID:
```kotlin
CASMobileAds.initialize(
    context = context,
    casId = CASMobileAds.TEST_ID, // [!code highlight]
)
```

You can also keep your own CAS ID and force test ads:
```kotlin
CASMobileAds.initialize(
    context = context,
    casId = casId,
    forceTestAds = true, // [!code highlight]
)
```

To enable it for debug builds only, pass your own build flag from each platform. One way is an `expect`
declaration in your shared module:
```kotlin
// commonMain
expect val isDebugBuild: Boolean

// androidMain
actual val isDebugBuild: Boolean = BuildConfig.DEBUG

// iosMain
actual val isDebugBuild: Boolean = Platform.isDebugBinary
```

```kotlin
CASMobileAds.initialize(
    context = context,
    casId = casId,
    forceTestAds = isDebugBuild, // [!code highlight]
)
```

## Enable test devices
If you want to do more rigorous testing with production-looking ads, you can configure your device as a test device and use your own manager id. Test devices can be added programmatically.

Follow the steps below to add your device as a test device.
1. Run an app configured with the CAS on device.
2. Check the log output for a message that looks like this:
```
To get test ads on this device, set "12345678901234567890123456789012"
```
3. Copy your alphanumeric test device ID to your clipboard.
4. Modify your code to set the test device ID through `testDeviceIds` before CAS initialization.
```kotlin
CASMobileAds.initialize(
    context = context,
    casId = casId,
    testDeviceIds = setOf("12345678901234567890123456789012"), // [!code highlight]
)
```
<Info>
Be sure to remove the code that sets these test devices before you release your app.
</Info>

5. Re-run your app.
6. Well done, ads on this device are safe to click. Requests, impressions, and clicks on ads in test mode will not show up in your account's reports.
```

### Impression Level Data

Source: https://production.docs.page/docs/kmp/impression-level-data

```mdx

CAS.AI SDK enables you to access detailed information for each impression through the impression callback APIs. The information includes, for example, which demand source served the ad, the expected or exact revenue associated with it. In addition, it contains granular details to allow you to analyze and, ultimately, optimize user acquisition strategies.

### CASAdContentInfo
The `CASAdContentInfo` structure contains information about a displayed ad.

In addition to the impression callback, each ad format exposes a `contentInfo` property. It is `null` before
the ad is loaded, except on `CASNativeAdContent` where the content info is always available.

```kotlin
val info: CASAdContentInfo? = interstitialAd.contentInfo
```

<Property name="format" type="CASAdFormat">
  The format of the ad that is shown.
</Property>

---

<Property name="sourceName" type="String">
  The display name of the mediated network that purchased the impression.
</Property>

---

<Property name="sourceUnitId" type="String">
  The Ad Unit ID from the mediated network that purchased the impression.
</Property>

---

<Property name="creativeId" type="String?" optional>
  The Creative ID associated with the ad, if available.
  You can use this ID to report creative issues to the Ad review team.
</Property>

---

<Property name="revenue" type="Double">
  The revenue generated from the impression, in USD.
  The revenue value may be either estimated or exact, depending on the precision specified by `revenuePrecision`.
</Property>

---

<Property name="revenuePrecision" type="CASAdRevenuePrecision">
  The precision type of the revenue field.
</Property>

---

<Property name="revenueTotal" type="Double">
  The accumulated value of user ad revenue in USD from all ad format impressions.
</Property>

---

<Property name="impressionDepth" type="Int">
  The total number of impressions across all ad formats for the current user, across all sessions.
</Property>

### Revenue precision
`CASAdRevenuePrecision` tells you how exact the `revenue` value is.

| Value | Meaning |
|---|---|
| `UNKNOWN` | There is insufficient data for CAS to calculate a revenue value. CAS returns $0 in revenue. |
| `PRECISE` | The revenue is provided as part of a real-time auction and is the most accurate value available. |
| `FLOOR` | The revenue is based on the manual CPM value entered for the waterfall instance. Actual revenue is expected to be 10-20% higher than this floor value. |
| `ESTIMATED` | The revenue is calculated from historical performance data. Estimates may differ from actual values by up to 10%. |

### Ad Impression callback
Every ad format exposes an `impressionCallback` property that accepts a `CASAdImpressionCallback`.
The same callback can be reused for all formats, because `CASAdContentInfo.format` tells you which one it was.

```kotlin
import com.cleveradssolutions.plugin.kmp.CASAdContentInfo
import com.cleveradssolutions.plugin.kmp.CASAdImpressionCallback

val impressionCallback = CASAdImpressionCallback { info: CASAdContentInfo ->
    // Called when an ad impression occurs.
    val adPlatform = "CAS"
    val adFormat = info.format.name
    val adSource = info.sourceName
    val adUnitName = info.sourceUnitId
    val value = info.revenue
    // All CAS revenue is sent in USD
    val currency = "USD"
}

appOpenAd.impressionCallback = impressionCallback
interstitialAd.impressionCallback = impressionCallback
rewardedAd.impressionCallback = impressionCallback
bannerContent.impressionCallback = impressionCallback
nativeAdContent.impressionCallback = impressionCallback
```

Banner ads additionally report impressions through `CASBannerAdContentCallback.onBannerAdImpression`, so you can
choose whichever fits your code better.

<Info>
All callbacks are invoked on the main thread. Because the callback lives in `commonMain`, the reporting code is
written once and runs on both platforms.
</Info>

### User ad summary
CAS counts the number of ad impressions and the total revenue of all formats at the time of a new impression.
```kotlin
val totalImpressions: Int = info.impressionDepth
val totalRevenue: Double = info.revenueTotal
```
<Info>
Progress is saved between sessions until the user clears your app's data.
</Info>

## Automatic collect ad revenue
The CAS SDK has features to automatically collect ad revenue to Google Analytics and Tenjin Analytics. Contact your account manager for details of enabling automatic events.

### Google Analytics
To measure ad revenue with Google Analytics:

1. Get started with [Firebase Analytics](https://firebase.google.com/docs/analytics/get-started).
2. Link your Firebase project to a Google Analytics account.

The SDK automatically logs [`ad_impression`](https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#public-static-final-string-ad_impression)
events whenever an ad is displayed.
Events include parameters such as ad platform, source, currency, and value.
Alternatively, CAS may log the event as `CAS_Impression`.

### Tenjin
To measure ad revenue with Tenjin Analytics, include the Tenjin SDK in each platform project.

<Tabs groupId="platform">
<TabItem label="Android" value="android">
The CAS Gradle plugin can add the Tenjin SDK for you:
```kotlin
// <project>/shared/build.gradle.kts
cas {
    includeTenjinSDK = true
}
```
</TabItem>

<TabItem label="iOS" value="ios">
Add the [Tenjin Swift Package](https://github.com/tenjin/tenjin-ios-sdk) to your Xcode project:
```
https://github.com/tenjin/tenjin-ios-sdk
```
</TabItem>
</Tabs>

CAS SDK automatically initializes the Tenjin SDK and sends ILRD if this option is enabled for your application.
```

### Initialize CAS SDK

Source: https://production.docs.page/docs/kmp/initialize-cas

```mdx

Before loading ads, have your app initialize the CAS Mobile Ads SDK by calling `CASMobileAds.initialize()`.
The call returns immediately and reports the result through a `CASInitializationListener`.

The `casId` is a unique identifier for the CAS content registered for your app on each platform.

```kotlin
import com.cleveradssolutions.plugin.kmp.CASInitializationListener
import com.cleveradssolutions.plugin.kmp.CASMobileAds

fun initializeAds(context: Any?) {
    CASMobileAds.initialize(
        // Android: an Activity, Application or any other Context. iOS: pass null.
        context = context,
        casId = "APP CAS ID",
        listener = CASInitializationListener { config ->
            if (config.error != null) {
                println("CAS Mobile Ads SDK initialization failed: ${config.error}")
            } else {
                println("CAS Mobile Ads SDK initialized in ${config.countryCode} country")
            }
        },
    )
}
```

<Warning>
The CAS ID is **different on each platform**, so shared code cannot use a single literal. Declare it per
platform as shown below.
</Warning>

## The CAS ID of each platform
On Android the CAS ID is your application package name, on iOS it is your App Store ID. Declare it with an
`expect` property so that common code stays platform agnostic:

```kotlin
// commonMain
expect val casId: String

// androidMain
actual val casId: String = "com.yourcompany.yourproject"

// iosMain
actual val casId: String = "123456789"
```

```kotlin
CASMobileAds.initialize(
    context = context,
    casId = casId, // [!code highlight]
)
```

<AccordionGroup>
<Accordion title="What is CAS ID on Android?">

In most cases, a `casId` is the same as your application package name.
- A [package name](https://developer.android.com/studio/build/application-id) uniquely identifies your app on the device and in the Google Play Store.
- The package name value is case-sensitive and is often referred to as an `APPLICATION_ID`.
- Find your app's package name in your module (app-level) Gradle file, usually `shared/build.gradle.kts` (example package name: `com.yourcompany.yourproject`).

You can read it from `BuildConfig` instead of hardcoding it:
```kotlin
// androidMain
actual val casId: String = BuildConfig.APPLICATION_ID
```

</Accordion>
<Accordion title="What is CAS ID on iOS?">

In most cases, a CAS ID is the same as your app store ID.
You can find an app store ID in the URL of your app’s Apple App Store URL. For example, if the URL is
`apps.apple.com/us/app/id123456789` then the app store ID is `123456789`.

</Accordion>
<Accordion title="I have not registered an app yet">

If you haven't created a CAS account and registered an app yet, now's a great time to do so at https://cas.ai

To experiment before that, use the demo CAS ID, which always serves test ads on every device:
```kotlin
CASMobileAds.initialize(
    context = context,
    casId = CASMobileAds.TEST_ID, // [!code highlight]
)
```

See [Enable test ads](kmp/enabling-test-ads) for the other ways to test safely.

</Accordion>
</AccordionGroup>

The `context` parameter is only used on Android. On iOS the value is ignored, so shared code can pass the
platform context it already has without branching.

<AccordionGroup>
<Accordion title="Where does the context come from?">

On Android, pass the `Activity` or `Application` you already have:
```kotlin
// androidMain
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent { App(context = this) }
    }
}
```

On iOS, there is no context to pass:
```kotlin
// iosMain
fun MainViewController() = ComposeUIViewController {
    App(context = null)
}
```

</Accordion>
</AccordionGroup>

If `initialize()` is not called, the first ad load automatically initializes the CAS Mobile Ads SDK with the
CAS ID defined in the ad instance arguments.

If an error occurs, the SDK will attempt automatic reinitialization internally. However, the listener will not
be invoked again with a subsequent result. For the most up-to-date result, call `initialize()` again at a later time.

You can check whether initialization has already completed:
```kotlin
val isReady: Boolean = CASMobileAds.isInitialized
```

<Error>
Do not initialize mediated advertising SDKs (CAS does that for you).
Not following this step will result in noticeable integration issues.
</Error>

## Initialization result
`CASInitializationResult` carries everything the SDK learned during initialization.

<Property name="error" type="String?">
Error message if initialization failed, or `null` if initialization completed successfully.
</Property>
<Property name="countryCode" type="String?">
Country code detected during initialization, if available.
</Property>
<Property name="isConsentRequired" type="Boolean">
Indicates whether consent is required for the user.
</Property>
<Property name="consentFlowStatus" type="CASConsentFlowStatus">
Current consent flow status.
</Property>

## Automatic user consent flow
To get consent for collecting personal data of your users, we suggest you use a built-in Consent Flow, which comes with
a pre-made consent form that you can easily present to your users. That means you no longer need to create your own consent window.

The user will see the consent flow when your app initializes the CAS SDK.
Once the user completes the flow, the initialization listener is invoked.

You can choose whether to `showConsentFormIfRequired` in the arguments of `initialize()`:
```kotlin
CASMobileAds.initialize(
    context = context,
    casId = casId,
    showConsentFormIfRequired = true, // [!code highlight]
    listener = CASInitializationListener { config ->
        if (config.consentFlowStatus == CASConsentFlowStatus.OBTAINED) {
            println("CAS Mobile Ads SDK obtain user consent")
        }
    },
)
```

You must wait until the user finishes the consent flow before you initialize third-party SDKs (such as MMPs or analytics SDKs). For this reason, initialize such SDKs from within your initialization-completion callback. If you were to initialize these third-party SDKs before the user completes the consent flow, these third-party SDKs would not be able to access relevant identifiers and you would suffer a material impact on measurement, reporting, and ad revenue.

<Info>
Read more about "Privacy options button" and "Debug geography" on the [CAS User Consent Flow page](kmp/user-consent-flow)
</Info>

## Always test with test ads
When building and testing your apps, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account.

By default, CAS initializes mediation in live mode. To enable test ad mode, set `forceTestAds` in the arguments of `initialize()`:
```kotlin
CASMobileAds.initialize(
    context = context,
    casId = casId,
    forceTestAds = true, // [!code highlight]
    testDeviceIds = setOf(
        "Your test device ID", // [!code highlight]
    ),
    listener = null,
)
```

You can also test in a release build by registering your device as a test device. Check the logs for your device's ID value.

For more information about how the CAS.AI SDK's test ads work, see [Enable test ads](kmp/enabling-test-ads)

## Prohibition on Personal Information from Children
Apps can be marked as child-directed or [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy) applicable through the CAS UI.

If the app has knowledge of specific individuals as being COPPA-applicable, it should make use of the `targetAudience` parameter in `initialize()`.
```kotlin
CASMobileAds.initialize(
    context = context,
    casId = casId,
    targetAudience = CASTaggedAudience.NOT_CHILDREN, // [!code highlight]
    listener = null,
)
```

Available values are `CASTaggedAudience.UNDEFINED`, `CASTaggedAudience.CHILDREN` and `CASTaggedAudience.NOT_CHILDREN`.

If your app targets both children and older users, all ads that may be shown to children must comply with COPPA.
To ensure compliance, a **neutral age screen** must be implemented so that ads unsuitable for children are only shown to appropriate audiences.
A neutral age screen is a tool—such as an age gate—that verifies a user’s age without encouraging them to misrepresent it, and prevents children from accessing content not intended for them.

## (Optional) Mediation extras
Additional key-value settings passed to the mediation networks.
```kotlin
CASMobileAds.initialize(
    context = context,
    casId = casId,
    mediationExtras = mapOf("key" to "value"), // [!code highlight]
    listener = null,
)
```

## (Optional) Retrieve the Version Number
To programmatically retrieve the SDK version number at runtime, CAS provides the following property:
```kotlin
val sdkVersion: String = CASMobileAds.sdkVersion
```

## (Optional) Debug logging
The enabled Debug Mode will display a lot of useful information for debugging about the states of the SDK
with the tag `CAS`. Disabling Debug Mode may improve application performance. Disabled by default.
```kotlin
CASMobileAds.debugLoggingEnabled = true
```

## (Optional) Trial ad-free interval
Defines the time interval, in seconds, starting from the moment of the initial app installation, during which users can use the application without ads being displayed while still retaining access to the Rewarded Ads format. Within this interval, users enjoy privileged access to the application's features without intrusive advertisements.

```kotlin
val secondsIn7Days = 604800
CASMobileAds.trialAdFreeInterval = secondsIn7Days
```

## Complete example
- [Initialize CASMobileAds example](https://github.com/cleveradssolutions/CAS-KMP/blob/main/cas-demo-app/src/commonMain/kotlin/com/cleveradssolutions/kmp/demo/screens/SetupScreen.kt)
```

### Interstitial Ads

Source: https://production.docs.page/docs/kmp/interstitial-ads

```mdx

Interstitial ads are full-screen ads that cover the interface of their host app.
They're typically displayed at natural transition points in the flow of an app, such as between screens.
When an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.

Interstitial Ad management is handled through the `CASInterstitialAd` class from `commonMain`.
The ad is presented by the native CAS.AI SDK on top of all app content, so it is not part of the Compose tree
and nothing has to be added to your UI.

CAS provides an option to enable `autoLoad` to simplify your app logic. Before using the ad, you should decide whether to enable `autoLoad`, or manually manage each ad loading cycle in your code.

When `autoLoad` is enabled, a new ad will be automatically loaded after each display, and loading failures will trigger automatic retry attempts.
```kotlin
val isAutoLoadEnabled = true
```

Manual load mode (`autoLoad = false`) is useful when you only need to show a single ad per app screen, and the screens change frequently.

Below is a diagram showing the ad lifecycle and how `autoLoad` affects it.

<Image zoom src="/assets/Lifecycle-Screen-Ad.png" alt="Diagram" height="500" />

## Create Ad instance
The following example creates and loads an interstitial ad:
```kotlin
import com.cleveradssolutions.plugin.kmp.CASAdContentInfo
import com.cleveradssolutions.plugin.kmp.CASAdFormat
import com.cleveradssolutions.plugin.kmp.CASError
import com.cleveradssolutions.plugin.kmp.CASInterstitialAd
import com.cleveradssolutions.plugin.kmp.CASMobileAds
import com.cleveradssolutions.plugin.kmp.CASScreenAdContentCallback

val interstitialAd = CASInterstitialAd(
    casId = "APP CAS ID",
    autoLoad = isAutoLoadEnabled,
    callback = object : CASScreenAdContentCallback {
        override fun onAdLoaded(ad: CASAdContentInfo) {
            // Called when an ad is successfully loaded.
            println("Interstitial ad loaded")
        }

        override fun onAdFailedToLoad(format: CASAdFormat, error: CASError) {
            // Called when an ad load failed.
            println("Interstitial ad failed to load: ${error.message}")
        }
    },
)
```

In Compose code, keep the instance across recompositions with `remember`:
```kotlin
@Composable
fun InterstitialScreen() {
    val interstitialAd = remember {
        CASInterstitialAd(casId = "APP CAS ID", autoLoad = true)
    }

    DisposableEffect(interstitialAd) {
        onDispose { interstitialAd.destroy() }
    }
}
```

Ad content may take some time to load after creating an ad instance. To ensure the ad displays instantly when needed, create the ad instance in advance. Use the `onAdLoaded` callback to be notified when the ad is ready for display.

## Ad content callbacks
`CASScreenAdContentCallback` declares the full ad lifecycle. Every method has a default empty implementation,
so override only the ones you need.

```kotlin
object : CASScreenAdContentCallback {
    override fun onAdLoaded(ad: CASAdContentInfo) {
        // Called when an ad is successfully loaded.
    }

    override fun onAdFailedToLoad(format: CASAdFormat, error: CASError) {
        // Called when an ad load failed.
    }

    override fun onAdFailedToShow(format: CASAdFormat, error: CASError) {
        // Called when the ad failed to show full screen content.
    }

    override fun onAdShowed(ad: CASAdContentInfo) {
        // Called when the ad showed the full screen content.
    }

    override fun onAdClicked(ad: CASAdContentInfo) {
        // Called when a click is recorded for an ad.
    }

    override fun onAdDismissed(ad: CASAdContentInfo) {
        // Called when the ad dismissed full screen content.
    }
}
```

Impressions are reported through a separate callback, which you can change at any time:
```kotlin
interstitialAd.impressionCallback = CASAdImpressionCallback { ad ->
    // Called when an impression occurs on the ad.
    println("Impression from ${ad.sourceName} with revenue ${ad.revenue}")
}
```

<Info>
- All callbacks are invoked on the main thread.
- Read more about the `CASAdContentInfo` structure in [Impression Level Data](kmp/impression-level-data).
- When an error occurs during ad impression, only `onAdFailedToShow` is executed. In this case `onAdDismissed` will not be executed, since the impression is not considered successful.
</Info>

## Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.

```kotlin
interstitialAd.placement = "BestPlace" // [!code highlight]
```

## Show Ad
Interstitial ads should be displayed during natural pauses in the flow of an app. Between app screens is a good example, or after the user completes a task.

You can choose when to show the ad by calling `show()`:
```kotlin
interstitialAd.show()
```

If the ad is not ready at that moment, the `onAdFailedToShow` callback will be triggered with a reason provided in the `CASError`.

You have the option to check `isLoaded` if it's required by your app's logic.
```kotlin
val isAdLoaded: Boolean = interstitialAd.isLoaded
```

### Auto Show Ad mode
CAS provides the option to automatically show a loaded ad when the user returns to the app. To enable this behavior, set the `autoShow` argument to `true`.
```kotlin
val interstitialAd = CASInterstitialAd(
    casId = "APP CAS ID",
    autoShow = true, // [!code highlight]
)
```

The mode can also be changed later through `interstitialAd.isAutoShowEnabled`.

## Release ad resource
Be sure to release ad resources if you’re no longer going to use the ad instance.
```kotlin
interstitialAd.destroy() // [!code highlight]
```

It may be useful to store the ad instance in a shared object for reuse across multiple screens. This way, you don't need to call `destroy()` and can show the already loaded ad without delay.

## Manual reload Ad
When you want to manually control ad loading, use `load()` on the created ad instance to retry loading with the same configuration.
```kotlin
interstitialAd.load()
```

Autoload can also be switched at runtime:
```kotlin
interstitialAd.isAutoLoadEnabled = false
```

## Minimum interval between impressions
The minimum interval between showing interstitial ads, in seconds.
Attempting to show a new interstitial ad before the interval has passed after the previous one was dismissed will trigger `onAdFailedToShow`.

```kotlin
interstitialAd.minInterval = 30 // [!code highlight]
```

By default, this interval is set to 0 seconds.

Note that the timer for the minimum interval is shared across all interstitial ad instances, but the minimum interval value may differ for each ad instance.

If you need to reset the minimum interval timer after showing a Rewarded Ad or an App Open Ad, you can call
`interstitialAd.restartInterval()` in the `onAdDismissed` callback of those ad formats.

```kotlin
interstitialAd.restartInterval()
```

By default, the interval before the first interstitial ad impression is ignored. Use this method to delay
displaying the ad by restarting the interval countdown.

## Mute Ad sounds
Indicates if the application’s audio is muted. Affects the initial mute state for fullscreen ads. Use this property only if your application has its own volume controls (e.g., custom music or sound effect muting).
```kotlin
CASMobileAds.adSoundsMuted = true
```
Not muted by default.

## Some best practices
#### Consider whether interstitial ads are the right type of ad for your app.
Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, like sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it's easy to present an interstitial ad without disrupting their experience. Make sure you consider at which points in your app's workflow you'll display interstitial ads and how the user is likely to respond.

#### Remember to pause the action when displaying an interstitial ad.
There are a number of different types of interstitial ads: text, image, video, and more. It's important to make sure that when your app displays an interstitial ad, it also suspends its use of some resources to allow the ad to take advantage of them. For example, when you make the call to display an interstitial ad, be sure to pause any audio output being produced by your app.

#### Allow for adequate loading time.
Just as it's important to make sure you display interstitial ads at an appropriate time, it's also important to make sure the user doesn't have to wait for them to load. Loading the ad in advance by calling `load()` before you intend to call `show()` can ensure that your app has a fully loaded interstitial ad at the ready when the time comes to display one.

#### Don't flood the user with ads.
While increasing the frequency of interstitial ads in your app might seem like a great way to increase revenue, it can also degrade the user experience and lower clickthrough rates. Make sure that users aren't so frequently interrupted that they're no longer able to enjoy the use of your app.

## Complete example
- [Interstitial ad example](https://github.com/cleveradssolutions/CAS-KMP/blob/main/cas-demo-app/src/commonMain/kotlin/com/cleveradssolutions/kmp/demo/screens/InterstitialExampleScreen.kt)
```

### Native Ads

Source: https://production.docs.page/docs/kmp/native-ads

```mdx

Native ads are ad assets presented to users through UI components that are native to the platform.
You decide the layout, so a native ad can match the look and feel of your app much more closely than a banner.

Native ads consist of three parts:
- `CASNativeAdLoader` requests one or more ads.
- `CASNativeAdContent` holds the assets of a single loaded ad.
- The `CASNativeAd` composable renders the assets you choose, or `CASNativeAdTemplate` renders a ready-made layout.

<Image zoom src="/assets/Lifecycle-Native-Ad.png" alt="Diagram" height="500" />

## Load Ad content
```kotlin
import com.cleveradssolutions.plugin.kmp.CASError
import com.cleveradssolutions.plugin.kmp.CASMobileAds
import com.cleveradssolutions.plugin.kmp.CASNativeAdContent
import com.cleveradssolutions.plugin.kmp.CASNativeAdContentCallback
import com.cleveradssolutions.plugin.kmp.CASNativeAdLoader

val loader = CASNativeAdLoader(
    casId = "APP CAS ID",
    startVideoMuted = true,
    callback = object : CASNativeAdContentCallback {
        override fun onNativeAdLoaded(ad: CASNativeAdContent) {
            // Keep the content and render it.
        }

        override fun onNativeAdFailedToLoad(error: CASError) {
            println("Native ad failed to load: ${error.message}")
        }
    },
)

loader.load()
```

`onNativeAdLoaded` is invoked once per loaded ad. To request several ads at once, pass the count to `load()`:
```kotlin
loader.load(maxNumberOfAds = 5)
```

In Compose code, hold the loaded content in state:
```kotlin
@Composable
fun NativeScreen() {
    var adContent by remember { mutableStateOf<CASNativeAdContent?>(null) }

    val loader = remember {
        CASNativeAdLoader(
            casId = "APP CAS ID",
            callback = object : CASNativeAdContentCallback {
                override fun onNativeAdLoaded(ad: CASNativeAdContent) {
                    adContent = ad
                }
            },
        )
    }

    LaunchedEffect(loader) { loader.load() }

    DisposableEffect(Unit) {
        onDispose { adContent?.destroy() } // [!code highlight]
    }

    adContent?.let { content ->
        // Render the ad, see below.
    }
}
```

## Ad content callbacks
Only `onNativeAdLoaded` is required, the rest have default empty implementations.

```kotlin
object : CASNativeAdContentCallback {
    override fun onNativeAdLoaded(ad: CASNativeAdContent) {
        // Called when an ad is successfully loaded.
    }

    override fun onNativeAdFailedToLoad(error: CASError) {
        // Called when an ad load failed.
    }

    override fun onNativeAdFailedToShow(ad: CASNativeAdContent, error: CASError) {
        // Called when the ad failed to present its assets.
    }

    override fun onNativeAdClicked(ad: CASNativeAdContent) {
        // Called when a click is recorded for an ad.
    }
}
```

Impressions are reported per content instance:
```kotlin
adContent.impressionCallback = CASAdImpressionCallback { ad ->
    println("Impression from ${ad.sourceName} with revenue ${ad.revenue}")
}
```

<Info>
Read more about the `CASAdContentInfo` structure in [Impression Level Data](kmp/impression-level-data).
</Info>

## Ad assets
`CASNativeAdContent` exposes the text assets so you can decide what your layout needs. Every asset except
`contentInfo` is optional and can be `null`, because each mediated network provides a different subset.

<Property name="headline" type="String?">
The primary headline of the ad. Required by most networks and should always be displayed.
</Property>
<Property name="body" type="String?">
The body text of the ad.
</Property>
<Property name="callToAction" type="String?">
The text of the call to action, for example "Install".
</Property>
<Property name="advertiser" type="String?">
The name of the advertiser.
</Property>
<Property name="price" type="String?">
The price of the promoted product.
</Property>
<Property name="store" type="String?">
The store the promoted app is distributed through.
</Property>
<Property name="starRating" type="Double?">
The rating of the promoted app, from 0 to 5.
</Property>
<Property name="reviewCount" type="String?">
The number of reviews of the promoted app.
</Property>
<Property name="adLabel" type="String?">
The localized "Ad" label that has to be shown next to the ad content.
</Property>
<Property name="isExpired" type="Boolean">
Whether the ad content has expired and should no longer be displayed.
</Property>
<Property name="contentInfo" type="CASAdContentInfo">
Information about the loaded ad, see [Impression Level Data](kmp/impression-level-data).
</Property>

Always check `isExpired` before rendering content that was loaded a while ago, and request a new ad instead of
showing an expired one.

## Display the ad
Once the content is loaded, render it in one of two ways.

<CardGroup>
<Card title="Custom layout" href="/kmp/native-ads-layout">
Arrange the assets yourself with the `CASNativeAd` composable and the `NativeAdScope` elements.
</Card>
<Card title="Ready-made templates" href="/kmp/native-ads-templates">
Render a complete native ad with `CASNativeAdTemplate` and style it with a few parameters.
</Card>
</CardGroup>


## AdChoices placement
The AdChoices icon placement is chosen when the loader is created.

```kotlin
val loader = CASNativeAdLoader(
    casId = "APP CAS ID",
    adChoicesPlacement = CASNativeAdChoicesPlacement.TOP_RIGHT, // [!code highlight]
    callback = callback,
)
```

## Start video muted
Whether the video of the main media asset starts muted. Enabled by default.

```kotlin
val loader = CASNativeAdLoader(
    casId = "APP CAS ID",
    startVideoMuted = false, // [!code highlight]
    callback = callback,
)
```

## Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.

```kotlin
val loader = CASNativeAdLoader(
    casId = "APP CAS ID",
    placement = "FeedItem", // [!code highlight]
    callback = callback,
)
```

## Release ad resource
Each loaded `CASNativeAdContent` owns native resources and has to be destroyed when it is no longer displayed.

```kotlin
adContent.destroy()
```

When you preload several ads, destroy every instance you do not display.

## Complete example
- [Native ad example](https://github.com/cleveradssolutions/CAS-KMP/blob/main/cas-demo-app/src/commonMain/kotlin/com/cleveradssolutions/kmp/demo/screens/NativeExampleScreens.kt)
```

### Native Ad custom layout

Source: https://production.docs.page/docs/kmp/native-ads-layout

```mdx

A custom layout gives you full control over how the ad assets are arranged, so a native ad can match the look
and feel of your app exactly. If you do not need that control, use the ready-made
[Native Ad templates](kmp/native-ads-templates) instead.

`CASNativeAd` registers your composable content with the native SDK, so clicks and impressions are tracked
correctly. Inside its content block, place the asset composables of `NativeAdScope`.

```kotlin
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.cleveradssolutions.plugin.kmp.composable.AdBodyText
import com.cleveradssolutions.plugin.kmp.composable.AdCallToAction
import com.cleveradssolutions.plugin.kmp.composable.AdChoices
import com.cleveradssolutions.plugin.kmp.composable.AdHeadlineText
import com.cleveradssolutions.plugin.kmp.composable.AdIconImage
import com.cleveradssolutions.plugin.kmp.composable.AdMedia
import com.cleveradssolutions.plugin.kmp.composable.CASNativeAd

CASNativeAd(
    adContent = adContent,
    modifier = Modifier.fillMaxWidth(),
) {
    Column {
        Row {
            AdIconImage(modifier = Modifier.size(48.dp))
            Column {
                AdHeadlineText()
                AdBodyText()
            }
            AdChoices()
        }
        AdMedia(modifier = Modifier.fillMaxWidth().height(180.dp))
        AdCallToAction(modifier = Modifier.fillMaxWidth())
    }
}
```

<Warning>
Render the asset composables of `NativeAdScope` only inside `CASNativeAd`. Drawing the asset values with your
own `Text` or `Image` composables prevents the SDK from registering clicks and impressions, which breaks
reporting and can be treated as invalid traffic.
</Warning>

## Available asset composables
| Composable | Asset |
|---|---|
| `AdHeadlineText()` | Headline |
| `AdBodyText()` | Body text |
| `AdCallToAction()` | Call to action button |
| `AdIconImage()` | Icon image |
| `AdMedia()` | Main media, image or video |
| `AdChoices()` | AdChoices overlay |
| `AdAdvertiserText()` | Advertiser name |
| `AdLabelText()` | "Ad" label |
| `AdPriceText()` | Price |
| `AdStoreText()` | Store name |
| `AdStarRating()` | Star rating |
| `AdReviewCountText()` | Review count |

The text composables accept the usual Compose text parameters, such as `color`, `fontSize`, `fontWeight`,
`textAlign` and `maxLines`, so they can be styled to match your design.

`AdMedia` additionally accepts a `scaleType` of `CASNativeScaleType`, and `AdCallToAction` accepts
`textColor`, `backgroundColor` and `shape`.
```

### Native Ads templates

Source: https://production.docs.page/docs/kmp/native-ads-templates

```mdx

Native templates are code-complete layouts for your native ads, designed for fast implementation and easy modification.
With native templates, the plugin provides prebuilt Android and iOS layouts for you, and you can customize the style
of the native assets from common Kotlin code.

Use `CASNativeAdTemplate` instead of `CASNativeAd` when you do not need a custom layout. The template picks its
internal layout from the size you give it:

1. If the height is greater than 500 dp, a large native ad layout is used.
<Image height="500" alt="Image" src="/assets/Native-Template-Screen.jpg" />

2. If the height is greater than 200 dp, a medium layout is used.
<Image width="300" alt="Image" src="/assets/Native-Template-MRec.jpg" />

3. Otherwise, a banner layout is used.
<Image width="300" alt="Image" src="/assets/Native-Template-Small.jpg" />

## Display the template
`maxWidth` and `maxHeight` are required, because they decide which layout the template uses.

```kotlin
import androidx.compose.ui.unit.dp
import com.cleveradssolutions.plugin.kmp.composable.CASNativeAdTemplate

CASNativeAdTemplate(
    adContent = adContent,
    maxWidth = 360.dp,
    maxHeight = 300.dp,
)
```

To fill the available width, read it from the layout:
```kotlin
BoxWithConstraints {
    CASNativeAdTemplate(
        adContent = adContent,
        maxWidth = maxWidth,
        maxHeight = 300.dp,
    )
}
```

[Loading the ad content](kmp/native-ads#load-ad-content) and releasing it with `destroy()` work exactly the same
as for a custom layout.

## Customize ad
The CAS Template can be customized by changing the colors of individual components and the font style.
All style parameters are optional, and `null` keeps the default of the template.

<Property name="backgroundColor" type="Color?">
The background color of the template.
</Property>
<Property name="primaryColor" type="Color?">
The primary color, used for the "Call to action" button background.
</Property>
<Property name="primaryTextColor" type="Color?">
The text color of the "Call to action" button.
</Property>
<Property name="headlineTextColor" type="Color?">
The headline text color.
</Property>
<Property name="headlineFontStyle" type="CASNativeTemplateFontStyle?">
The headline text font style.
</Property>
<Property name="secondaryTextColor" type="Color?">
The color of the remaining text assets.
</Property>
<Property name="secondaryFontStyle" type="CASNativeTemplateFontStyle?">
The font style of the remaining text assets.
</Property>

The following example renders the template with a full custom style:
```kotlin
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.cleveradssolutions.plugin.kmp.CASNativeTemplateFontStyle
import com.cleveradssolutions.plugin.kmp.composable.CASNativeAdTemplate

CASNativeAdTemplate(
    adContent = adContent,
    maxWidth = 360.dp,
    maxHeight = 300.dp,
    backgroundColor = Color.White,
    primaryColor = Color(0xFF2563EB),
    primaryTextColor = Color.White,
    headlineTextColor = Color.Black,
    headlineFontStyle = CASNativeTemplateFontStyle.BOLD,
    secondaryTextColor = Color.DarkGray,
    secondaryFontStyle = null,
)
```

**Continue to use Native Ad as usual.**
```

### Rewarded Ads

Source: https://production.docs.page/docs/kmp/rewarded-ads

```mdx

Rewarded ads are full-screen ads that users choose to watch in exchange for in-app rewards.
Unlike other formats, the user has to opt in and watch the ad to completion before the reward is granted.

Rewarded Ad management is handled through the `CASRewardedAd` class from `commonMain`.
The ad is presented by the native CAS.AI SDK on top of all app content, so it is not part of the Compose tree.

<Image zoom src="/assets/Lifecycle-Rewarded-Ad.png" alt="Diagram" height="500" />

## Create Ad instance
```kotlin
import com.cleveradssolutions.plugin.kmp.CASAdContentInfo
import com.cleveradssolutions.plugin.kmp.CASAdFormat
import com.cleveradssolutions.plugin.kmp.CASError
import com.cleveradssolutions.plugin.kmp.CASMobileAds
import com.cleveradssolutions.plugin.kmp.CASRewardedAd
import com.cleveradssolutions.plugin.kmp.CASScreenAdContentCallback

val rewardedAd = CASRewardedAd(
    casId = "APP CAS ID",
    autoLoad = true,
    callback = object : CASScreenAdContentCallback {
        override fun onAdLoaded(ad: CASAdContentInfo) {
            println("Rewarded ad loaded")
        }

        override fun onAdFailedToLoad(format: CASAdFormat, error: CASError) {
            println("Rewarded ad failed to load: ${error.message}")
        }
    },
)
```

When `autoLoad` is enabled, a new ad is automatically loaded after each display, and loading failures trigger
automatic retry attempts. Set it to `false` to control every load yourself with `load()`.

In Compose code, keep the instance across recompositions with `remember` and release it on dispose:
```kotlin
@Composable
fun RewardedScreen() {
    val rewardedAd = remember {
        CASRewardedAd(casId = "APP CAS ID", autoLoad = true)
    }

    DisposableEffect(rewardedAd) {
        onDispose { rewardedAd.destroy() }
    }
}
```

## Show Ad and grant the reward
Unlike the other full screen formats, `show()` requires a `CASRewardEarnedListener`. It is invoked only when
the user has watched enough of the ad to earn the reward.

```kotlin
rewardedAd.show(
    rewardEarnedListener = CASRewardEarnedListener { ad ->
        // Reward the user here.
        println("User earned reward from ${ad.sourceName}")
    },
)
```

<Warning>
`onUserEarnedReward` is the only correct place to grant a reward. Do not grant it from `onAdDismissed`,
because the user may dismiss the ad before completing it.
</Warning>

If the ad is not ready at that moment, the `onAdFailedToShow` callback is triggered with a reason provided in
the `CASError`, and the reward listener is not invoked.

You have the option to check `isLoaded` if it's required by your app's logic.
```kotlin
val isAdLoaded: Boolean = rewardedAd.isLoaded
```

## Ad content callbacks
`CASRewardedAd` uses the same `CASScreenAdContentCallback` as the other full screen formats. Every method has a
default empty implementation, so override only the ones you need.

```kotlin
object : CASScreenAdContentCallback {
    override fun onAdLoaded(ad: CASAdContentInfo) {}
    override fun onAdFailedToLoad(format: CASAdFormat, error: CASError) {}
    override fun onAdFailedToShow(format: CASAdFormat, error: CASError) {}
    override fun onAdShowed(ad: CASAdContentInfo) {}
    override fun onAdClicked(ad: CASAdContentInfo) {}
    override fun onAdDismissed(ad: CASAdContentInfo) {}
}
```

Impressions are reported through a separate callback:
```kotlin
rewardedAd.impressionCallback = CASAdImpressionCallback { ad ->
    println("Impression from ${ad.sourceName} with revenue ${ad.revenue}")
}
```

<Info>
Read more about the `CASAdContentInfo` structure in [Impression Level Data](kmp/impression-level-data).
</Info>

## Server-Side Verification
Server-side verification callbacks let your server verify that the user has earned the reward before you grant it.
Set the custom data that CAS.AI sends to your server together with the reward notification.

```kotlin
rewardedAd.serverSideVerificationData = "user-123" // [!code highlight]
```

## Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.

```kotlin
rewardedAd.placement = "LevelComplete" // [!code highlight]
```

## Manual reload Ad
When you want to manually control ad loading, use `load()` on the created ad instance to retry loading with the same configuration.
```kotlin
rewardedAd.load()
```

Autoload can also be switched at runtime:
```kotlin
rewardedAd.isAutoLoadEnabled = false
```

## Release ad resource
Be sure to release ad resources if you’re no longer going to use the ad instance.
```kotlin
rewardedAd.destroy() // [!code highlight]
```

## Reset the interstitial interval
Showing a rewarded ad does not reset the [minimum interval](kmp/interstitial-ads#minimum-interval-between-impressions)
of your interstitial ads. If you want the interval to start counting from the rewarded impression, call
`restartInterval()` on your interstitial instance from `onAdDismissed`:

```kotlin
override fun onAdDismissed(ad: CASAdContentInfo) {
    interstitialAd.restartInterval()
}
```

## Ad-free users still get rewarded ads
The [trial ad-free interval](kmp/initialize-cas#optional-trial-ad-free-interval) suppresses other ad formats for
new users, but keeps Rewarded Ads available, so the reward mechanics of your app keep working from the first launch.

## Complete example
- [Rewarded ad example](https://github.com/cleveradssolutions/CAS-KMP/blob/main/cas-demo-app/src/commonMain/kotlin/com/cleveradssolutions/kmp/demo/screens/RewardedExampleScreen.kt)
```

### Targeting options

Source: https://production.docs.page/docs/kmp/targeting-options

```mdx

You can now easily tailor the way you serve your ads to fit a specific audience!
You’ll need to inform our servers of the users’ details so the SDK will know to serve ads according
to the segment the user belongs to.

All options are available from common code through `CASMobileAds.targetingOptions`, and every one of them is
optional.

<Warning>
Targeting options must be set **before** [initializing the SDK](kmp/initialize-cas), otherwise the first ad
requests will not take them into account.
</Warning>

### User ID
The user ID is a unique identifier supplied by your application and must be static for each user across sessions.
```kotlin
CASMobileAds.targetingOptions.userId = "user-hash-code"
```

<Warning>
Your user ID should not contain any personally identifiable information such as an email address, screen name, Android ID (AID), or Google Advertising ID (GAID).
</Warning>

### User Age
Set the user age. Limitation: 1-99. By default `0` is 'unknown'.

```kotlin
CASMobileAds.targetingOptions.age = 12
```

### User Gender
Set targeting to the user’s gender. Available values are `CASGender.UNKNOWN`, `CASGender.MALE` and `CASGender.FEMALE`.

```kotlin
CASMobileAds.targetingOptions.gender = CASGender.MALE
```

### User Location auto collection
Collect from the device the latitude and longitude coordinates truncated to the hundredths decimal place.
- Collect only if your application already has the relevant end-user permissions.
- Does not collect if the target audience is children.
- Disabled by default.

```kotlin
CASMobileAds.targetingOptions.locationCollectionEnabled = true
```

<Warning>
Do not use Location just for advertising. Your app should have a valid use case for it as well.
</Warning>

### App Keywords
Set a list of keywords, interests, or intents related to your application. Words or phrases describe
the current activity of the user for targeting purposes.

```kotlin
CASMobileAds.targetingOptions.keywords = setOf("puzzle", "casual game")
```

### App Content URL
Set the content URL for a website whose content matches the app's primary content. This website content is used for targeting and brand safety purposes. Limitation: max URL length 512.

```kotlin
CASMobileAds.targetingOptions.contentUrl = "https://example.com/related-content"
```
```

### User Consent Flow

Source: https://production.docs.page/docs/kmp/user-consent-flow

```mdx


<Info>
It is optional to use the CMP flow included with the CAS SDK. If you integrate your own CMP flow, make sure that flow completes before you initialize the CAS SDK.
</Info>

<Info>
If you implement a CMP that is compliant with IAB TCF v2 ([Transparency & Consent Framework](https://iabeurope.eu/tcf-2-0/)) for your user consent flow, the CAS SDK supports sending the TCF v2 consent to networks. In this case, the CAS Consent Flow will not be shown to the user.
</Info>

In order for CAS and our ad providers to deliver ads that are more relevant to your users, as a mobile app publisher, you need to collect explicit user consent for use of personal data in the regions covered by GDPR, CCPA, LGPD, PIPEDA.

### 1. Opt-in consent for the collection and use of personal data in the regions covered by GDPR, CCPA, LGPD, PIPEDA.
Any businesses established are required to comply with GDPR in Europe, CCPA in California, LGPD in Brazil, PIPEDA in Canada or risk facing heavy fines.

Keep in mind that it’s best to contact qualified legal professionals, if you haven’t done so already, to get more information and be well-prepared for compliance.

Read more about:
- GDPR - [General Data Protection Regulation](https://gdpr-info.eu)
- CCPA - [The California Consumer Privacy Act](https://theccpa.org)
- LGPD - [General Personal Data Protection Act](https://lgpd-brazil.info)
- PIPEDA - [The Personal Information Protection and Electronic Documents Act](https://www.priv.gc.ca/en/privacy-topics/privacy-laws-in-canada/the-personal-information-protection-and-electronic-documents-act-pipeda/)

<Image height="400" alt="image" src="/assets/User-Consent-Flow-1.png" />


#### Users will not see the Consent dialog if at least one of following is true
- Users located in regions that are not covered by information protection
- Users who are subject to COPPA restrictions.

### 2. Asking user permission to track them or access their device’s advertising identifier
With iOS 14.5 and later, you need to receive the user’s permission through the `AppTrackingTransparency` framework in order to track them or access their device’s advertising identifier. Read more about Asking Permission to Track and AppTrackingTransparency Framework on [Apple developer page](https://developer.apple.com/app-store/user-privacy-and-data-use/)

<Warning>
If an app does not present this request, the IDFA will automatically be zeroed out, which may lead to a significant loss in ad revenue.
</Warning>

#### Users will not see the ATT request if at least one of the following is true
- Users using iOS versions below 14.5
- Users who have indicated that they do not allow apps to ask to track them, by setting *Settings > Privacy, Allow Apps to Request to Track*
- Users with child accounts, or who are under age 18, who are signed in via their Apple ID
- Users who have already answered so far
- The app does not have a usage tracking description in **Info.plist** under `NSUserTrackingUsageDescription` key

## Automatic consent flow
The automatic consent flow is enabled by default and described on the [CAS initialization page](kmp/initialize-cas).

## Manual consent flow
Call `CASMobileAds.showConsentForm()` from common code. With `ifRequiredOnly = true` the SDK loads a form and
immediately presents it only when consent is required. The dismiss listener is invoked after the form is
dismissed, or immediately when consent is not required.

```kotlin
import com.cleveradssolutions.plugin.kmp.CASConsentFlowStatus
import com.cleveradssolutions.plugin.kmp.CASConsentFormDismissListener
import com.cleveradssolutions.plugin.kmp.CASMobileAds

CASMobileAds.showConsentForm(
    ifRequiredOnly = true,
    dismissListener = CASConsentFormDismissListener { status ->
        if (status == CASConsentFlowStatus.OBTAINED) {
            // User consent obtained.
        }
    },
)
```

<Warning>
`showConsentForm()` must be called from the main thread.
</Warning>

| CASConsentFlowStatus | Description                                                        |
| -------------------- | ------------------------------------------------------------------ |
| `UNKNOWN`            | The consent flow status is not known yet.                          |
| `OBTAINED`           | User consent obtained. Personalized vs non-personalized undefined. |
| `NOT_REQUIRED`       | User consent not required.                                         |
| `UNAVAILABLE`        | User consent unavailable.                                          |
| `INTERNAL_ERROR`     | There was an internal error.                                       |
| `NETWORK_ERROR`      | There was an error loading data from the network.                  |
| `CONTEXT_INVALID`    | There was no valid context to present the form.                    |
| `FLOW_STILL_SHOWING` | There was an error with another form still being displayed.         |

<Warning>
Caching the consent status in your app, or a previously saved consent string, could lead to a [TCF 3.3](https://support.google.com/admanager/answer/9999955) error if consent is expired.
</Warning>

## Privacy options button
Some consent forms require the user to modify their consent at any time. Adhere to the following steps to implement a privacy options button if required.

1. Implement a UI element, such as a button on your app's settings screen, that can trigger a privacy options form.
2. Once initialization completes, check the consent flow status to determine whether to display that UI element.
3. When a user interacts with your UI element, call `showConsentForm()` with `ifRequiredOnly = false` so the user can update their privacy options at any time.

```kotlin
@Composable
fun SettingsScreen() {
    var isConsentObtained by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        CASMobileAds.initialize(
            context = context,
            casId = casId,
            listener = CASInitializationListener { config ->
                isConsentObtained = config.consentFlowStatus == CASConsentFlowStatus.OBTAINED // [!code highlight]
            },
        )
    }

    if (isConsentObtained) {
        Button(
            onClick = {
                CASMobileAds.showConsentForm(
                    ifRequiredOnly = false, // [!code highlight]
                    dismissListener = CASConsentFormDismissListener { status ->
                        isConsentObtained = status == CASConsentFlowStatus.OBTAINED
                    },
                )
            },
        ) {
            Text("Privacy options")
        }
    }
}
```

## Debug geography
The SDK provides a way to test your app's behavior as though the device were located in the EEA or UK using the
`CASConsentDebugGeography` enum.

| CASConsentDebugGeography | Description                                                |
| ------------------------ | ---------------------------------------------------------- |
| `DISABLED`               | Let the system determine the user's geography.             |
| `EEA`                    | Treat the device as located in the European Economic Area. |
| `REGULATED_US_STATE`     | Treat the device as located in a regulated US state.       |
| `OTHER`                  | Treat the device as located outside regulated regions.     |

Specify it in the SDK initialization arguments, and the setting will be applied only for test sessions.
```kotlin
CASMobileAds.initialize(
    context = context,
    casId = casId,
    forceTestAds = isDebugBuild,
    debugGeography = CASConsentDebugGeography.EEA, // [!code highlight]
)
```

If you're showing the Consent Flow manually, define the `debugGeography` argument, and the setting will remain
active even for production sessions. Leave it as `DISABLED` to allow the system to determine the user's geography automatically.
```kotlin
CASMobileAds.showConsentForm(
    debugGeography = if (isDebugBuild) { // [!code highlight]
        CASConsentDebugGeography.EEA // [!code highlight]
    } else { // [!code highlight]
        CASConsentDebugGeography.DISABLED // [!code highlight]
    },
)
```

<Info>
Debug settings only take effect when test ads are enabled.
</Info>

## Meta Audience Network Data Processing Options for Users in California
The CAS does not support your handling of CCPA opt-out values for Meta Audience Network, you must work directly with the network for the purposes of your obligations for CCPA compliance.

To learn how to implement Meta Audience Network’s “Limited Data Use” flag, read the [Additional Meta AudienceNetwork steps](kmp/additional-meta-audiencenetwork-steps).
```

### Ad errors

Source: https://production.docs.page/docs/reactnative/ad-errors

```mdx

In cases where an ad fails to load/show, a callback is called which provides a `AdError` object.

AdError is commonly used in ad-related callbacks such as `AdFailedToLoadEvent` or `AdFailedToShowEvent`.

Use `AdError.code` to retrieve the error code.   
Use `AdError.message` to get a human-readable error description.   

See `code` constants for all available error codes.

| Code | AdErrorCode        | Description                                                                                                                                                                                            |
| ---- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 0    | InternalError      | Indicates an internal error occurred.                                                                                                                                                                  |
| 1    | NotReady           | Indicates that ads are not ready to be shown. Ensure to call the appropriate ad loading method or use automatic load mode. If using automatic load mode, wait a little longer for ads to be ready.     |
| 2    | Rejected           | Indicates that the device is rejected for services. Services may not be available for some devices that do not meet the requirements. For example, the country or version of the OS.                   |
| 3    | NoFill             | Indicates that no ads are available to be served. If ads are visible in test ads mode, your implementation is correct, and ads will be served once live.                                               |
| 6    | ReachedCap         | Indicates that the ad creative has reached its daily cap for the user. This is typically relevant for cross-promotion ads only.                                                                        |
| 7    | NotInitialized     | Indicates that the CAS SDK is not initialized. Ensure to add CAS initialization code.                                                                                                                  |
| 8    | Timeout            | Indicates a timeout error occurred because the advertising source did not respond in time. The system will continue waiting for a response, which may delay ad loading or cause a loading error.       |
| 9    | NoConnection       | Indicates that there is no internet connection available, which prevents ads from loading.                                                                                                             |
| 10   | ConfigurationError | Indicates that there is a configuration error in one of the mediation ad sources. Report this error to your support manager for further assistance.                                                    |
| 11   | NotPassedInterval  | Indicates that the interval between impressions of interstitial ads has not yet passed. This error may also occur if a trial ad-free interval has been defined and has not yet passed since app start. |
| 12   | AlreadyDisplayed   | Indicates that another fullscreen ad is currently being displayed, preventing new ads from showing. Review your ad display logic to avoid duplicate impressions.                                       |
| 13   | NotForeground      | Indicates that ads cannot be shown because the application is not currently in the foreground.                                                                                                         |
```

### Additional Meta AudienceNetwork steps

Source: https://production.docs.page/docs/reactnative/additional-meta-audiencenetwork-steps

```mdx

## Data Processing Options for US Users
Meta Audience Network Data Processing Options for US Users Limited Data Use is a data processing option that gives you more control over how your data is used in Meta’s systems and better supports your compliance efforts with various US state privacy regulations. To utilize this feature, you must proactively enable Limited Data Use.
Visit [Meta’s developer documentation](https://developers.facebook.com/docs/marketing-apis/data-processing-options) for details.

If you do not want to enable Limited Data Use (LDU) mode, pass an empty string as a value of mediation extras with key `FB_dp` in initialize method:
```ts
await CASMobileAds.initialize('YOUR_CAS_ID', {
  mediationExtras: { FB_dp: '' }, // [!code highlight]
});
```
To enable LDU for users and specify user geography, set `'LDU'` to `mediationExtras`:

```ts
await CASMobileAds.initialize('YOUR_CAS_ID', {
  mediationExtras: { FB_dp: 'LDU' }, // [!code highlight]
});
```
```

### App Open Ads

Source: https://production.docs.page/docs/reactnative/app-open-ads

```mdx

App open ads are a special ad format intended for publishers wishing to monetize their app load screens.
App open ads can be closed at any time, and are designed to be shown when your users bring your app to the foreground.
App open ads automatically show a small branding area so users know they're in your app.

AppOpen Ad management in React code is handled through the `AppOpenAd` class which extends the shared fullscreen ad logic.
The AppOpen ad is displayed as an overlay on top of all app content and cannot be added to the ReactNative component tree.

```ts
import { AppOpenAd } from 'react-native-cas';
```

Below is a diagram showing the ad lifecycle and how autoload affects it.

<Image zoom src="/assets/Lifecycle-Screen-Ad.png" alt="Diagram" height="500" />

## Load Ad
CAS provides an option to enable autoload to simplify your app logic. 
Before using the ad, you should decide whether to enable autoload, or manually manage each ad loading cycle in your code.

When autoload is enabled, a new ad will be automatically loaded after each display, and loading failures will trigger automatic retry attempts.
```ts
useEffect(() => {
  AppOpenAd.setAutoloadEnabled(true);
}, []);
```

Manual load mode is useful when you only need to show a single ad per app screen, and the screens change frequently.

When you want to manually control ad loading, use the `loadAd()` function.
```ts
useEffect(() => {
  AppOpenAd.loadAd();
}, []);
```

Ad content may take some time to load after creating an ad instance.
To ensure the ad displays instantly when needed, load the ad instance in advance.

Use the `addAdLoadedEventListener` event to be notified when the ad is ready for display.

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.

```ts
useEffect(() => {
  RewardedAd.setPlacement("BestPlace"); // [!code focus] 
}, []);
```

## Ad content callbacks
`AppOpenAd` provides several optional event listeners for the ad lifecycle.

```ts
useEffect(() => {
  const unsubscribeLoaded = AppOpenAd.addAdLoadedEventListener(() => {
    // Called when an ad is successfully loaded. 
    console.log('Loaded');
  });
  const unsubscribeFailedToLoad = AppOpenAd.addAdFailedToLoadEventListener((error) => {
    // Called when an ad load failed. 
    console.log('Load failed:', error);
  });
  const unsubscribeFailedToShow = AppOpenAd.addAdFailedToShowEventListener((error) => {
    // Called when the ad failed to show full screen content. 
    console.log('Failed to show:', error);
  });
  const unsubscribeShowed = AppOpenAd.addAdShowedEventListener(() => {
    // Called when the ad showed the full screen content. 
    console.log('Showed');
  });
  const unsubscribeClicked = AppOpenAd.addAdClickedEventListener(() => {
    // Called when a click is recorded for an ad.
    console.log('Clicked');
  });
  const unsubscribeImpression = AppOpenAd.addAdImpressionEventListener((info: AdContentInfo) => {
    // Called when an impression occurs on the ad.
    console.log('Impression', info);
  });
  const unsubscribeDismissed = AppOpenAd.addAdDismissedEventListener(() => {
    // Called when the ad dismissed full screen content. 
    console.log('Dismissed');
  });

  return () => {
    unsubscribeLoaded();
    unsubscribeFailedToLoad();
    unsubscribeFailedToShow();
    unsubscribeShowed();
    unsubscribeDismissed();
    unsubscribeImpression();
    unsubscribeClicked();
  };
}, []);
```

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](reactnative/impression-level-data).
- When an error occurs during ad impression, only `AdFailedToShowEvent` is triggered.  
  In this case, `AdDismissedEvent` will not be executed since the impression is not considered successful.
</Info>

## Show Ad
App open ads help you monetize your app's loading screen, when the app first launches and during app switches, but it's important to keep best practices in mind so that your users enjoy using your app. It's best to:
- Show your first app open ad after your users have used your app a few times.
- Show app open ads during times when your users would otherwise be waiting for your app to load.
- If a user returns to your app after having left it by clicking on an app open ad, it makes sure they're not presented with another app open ad.

You can choose when to show the ad by calling `show()`:
```ts
AppOpenAd.showAd();
```

If the ad is not ready at that moment, the `AdFailedToShowEvent` will be triggered with a reason provided in the `AdError`.

You have the option to check `isAdLoaded()` if it's required by your app's logic.
```ts
const isAdLoaded = await AppOpenAd.isAdLoaded();
```

### Auto Show mode
CAS provides the option to automatically show a loaded ad when the user returns to the app. 

To enable this behavior, set autoshow enabled:
```ts
AppOpenAd.setAutoshowEnabled(true);
```

## Release ad resource
Release ad resources when no longer needed.

```ts
useEffect(() => {
  return () => {
    AppOpenAd.destroy();
  };
}, []);
```

## Mute Ad sounds
Indicates if the application’s audio is muted. Affects initial mute state for fullscreen ads. Use this method only if your application has its own volume controls (e.g., custom music or sound effect muting).

```ts
CASMobileAds.setAdSoundsMuted(true);
```

Not muted by default.

## Cold starts and Loading screens
There is a delay between when you request an ad and when you receive an ad to show. 
If you do not design your app well, the user may briefly see your app and then be surprised by an out-of-context ad. 
Prevent this bad user experience. You can handle cold starts by showing a loading screen before any app content, and then showing the ad after the loading screen. 
If your app shows any app content after the loading screen, do not show the ad.

## Best Practices
- When an app open ad is not yet loaded (i.e. on cold start), load it first. Load any other ad formats later so that you avoid loading them in parallel with the app open ad. Loading multiple ad formats in parallel is not good for the device’s resources or for ad demand SDKs.
- If you have a loading screen under the app open ad, and your loading screen completes loading before the ad is dismissed, you may want to dismiss your loading screen in the `AdDismissedEvent` and `AdFailedToShowEvent` listeners.
- Wait a variable number of days after initial install to show on cold start.
- Only show an ad if the user backgrounds the app for a certain amount of time (i.e. 30 seconds).
- If you show a cold start ad, do not show soft launch app open ads or interstitials for a certain amount of time.
- Include a call-out to the user that tells them they will see an ad in the Splash/Loading screen. For example: “Watch an ad from their sponsor while the app loads.”

## Complete example
- [AppOpen ad example](https://github.com/cleveradssolutions/CAS-ReactNative/blob/main/example/src/AppOpenExample.tsx)
```

### Banner Ads

Source: https://production.docs.page/docs/reactnative/banner-ads

```mdx

Banner Ad units display rectangular ads that occupy a portion of an app's layout.
They can refresh automatically after a set period of time.
This means users view a new ad at regular intervals, even if they stay on the same screen in your app.
They're also the simplest ad format to implement.

Banner Ad management in **React Native** is handled through the `BannerAdView` component from **react-native-cas**,
which represents an ad view used directly in JSX.

```tsx
import { BannerAdView, BannerAdSize } from 'react-native-cas';
```

CAS provides an option to enable `autoReload` to simplify your app logic. The `autoReload` is enabled by default, loading failures will trigger automatic retry attempts.
You should decide whether to enable `autoReload`, or manually manage each ad loading cycle in your code.

Also, banner ads support automatic `refreshInterval` regardless of the `autoReload` setting.

Below is a diagram showing the ad lifecycle and how `autoReload` and `refreshInterval` affect it.

<Image zoom src="/assets/Lifecycle-Banner-Ad.png" alt="Diagram" height="500" />


## Choose the Ad size
To add a banner ad, you need to specify the ad size. To do this, choose one of the `AdSize` from the list below:

1. **Adaptive banner** ads have a fixed aspect ratio for the maximum width. 
The adaptive size calculates the optimal height for that width with an aspect ratio similar to 320x50. 
By default, the full screen width will be used. You can limit width by specifying a `maxWidth` in the parameters.
```ts
const adSize = BannerAdSize.ADAPTIVE;
```

2. **Inline banner** ads have a desired width and a maximum height, useful when you want to limit the banner's height. 
Inline banners are larger and taller compared to adaptive banners. They have variable height, including Medium Rectangle size, 
and can be as tall as the device screen. Specify the `maxWidth` and `maxHeight` dimensions to limit the ad size.
```ts
const adSize = BannerAdSize.INLINE;
```

3. **Smart** selects the optimal dimensions depending on the device type. For mobile devices, it returns 320x50, while for tablets, it returns 728x90. In the UI, these banners occupy the same amount of space regardless of device type.
```ts
const adSize = BannerAdSize.SMART;
```

4. **Medium Rectangle** has a fixed size of 300x250.
```ts
const adSize = BannerAdSize.MREC;
```

5. **Leaderboard** has a fixed size of 728x90 and is allowed on tablets only.
```ts
const adSize = BannerAdSize.LEADERBOARD;
```

6. **Standard Banner** has a fixed size of 320x50 and is the minimum ad size
```ts
const adSize = BannerAdSize.BANNER;
```

## Show Ad View
`BannerAdView` is a React component and can be used like any other view.

```tsx
<BannerAdView 
  size={adSize}
  maxWidth={undefined}
  maxHeight={undefined}
  autoReload={true} 
/>
```

The ad content will be loaded automatically as soon as the view is mounted. 
Keep in mind that loading the ad takes some time, so avoid frequently unmounting and remounting the view.

While the ad is loading, the widget will have a size of (1x1). When the ad loads, the widget will automatically adopt the selected size.

The size of the container in which you place your ad must be at least as large as the AdSize. Any padding effectively decreases the size of your container.

## Ad content callbacks
`BannerAdView` supports lifecycle callbacks via props:

```tsx
const onAdLoadedCallback = useCallback((data: AdViewInfo) => {
  // Called when an ad is successfully loaded. 
  console.log('Banner Ad loaded', data);
}, []);

const onAdFailedCallback = useCallback((err: AdError) => {
  // Called when an ad load failed. 
  console.log('Banner Ad load failed', err);
}, []);

const onAdClickedCallback = useCallback(() => {
  // Called when a click is recorded for an ad.
  console.log('Banner Ad clicked');
}, []);

const onAdImpressionCallback = useCallback((info: AdContentInfo) => {
  // Called when an impression occurs on the ad.  
  console.log('Banner Ad impression', info);
}, []);

return <BannerAdView
  size={adSize}
  onAdViewLoaded={onAdLoadedCallback}
  onAdViewFailed={onAdFailedCallback}
  onAdViewImpression={onAdClickedCallback}
  onAdViewClicked={onAdImpressionCallback}
/>
```

<Info>
Read more about `AdContentInfo` structure in [Impression Level Data](reactnative/impression-level-data).
</Info>

## Ad refresh interval
The automatic refresh interval determines how often a new ad request is generated. 
Once the interval elapses, a new ad will automatically load and display.

The interval countdown runs only while the ad is visible on screen. 

Set a custom refresh interval longer than 10 seconds, or 0 to disable refresh option. 
Default refresh interval is 30 seconds.

Override the automatic refresh interval in `refreshInterval` property:
```tsx
<BannerAdView
  size={adSize}
  refreshInterval={30} // [!code highlight]
/>
```
Set `refreshInterval={0}` to disable. Default interval **30 seconds**.

## Manual reload Ad
When you want to manually control ad loading, use the `loadAd()` function on the `BannerAdViewRef` to retry loading with the same configuration.

```tsx
const bannerAdRef = useRef<BannerAdViewRef>(null); // [!code highlight]
const retryTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

useEffect(() => {
  return () => {
    if (retryTimer.current) clearTimeout(retryTimer.current);
    retryTimer.current = null;
  };
}, []);

const onAdLoadedCallback = useCallback((data: AdViewInfo) => {
  if (retryTimer.current) {
    clearTimeout(retryTimer.current);
    retryTimer.current = null;
  }
}, []);

const onAdFailedCallback = useCallback((err: AdError) => {
  if (retryTimer.current) clearTimeout(retryTimer.current);
    retryTimer.current = setTimeout(() => {
      retryTimer.current = null;
      bannerAdRef.current?.loadAd(); // [!code highlight]
    }, 10000);
}, []);

return <BannerAdView 
  ref={bannerAdRef} 
  size={adSize} 
  autoReload={false}
  onAdViewLoaded={onAdLoadedCallback}
  onAdViewFailed={onAdFailedCallback}
/>
```

## BannerAdView props
<Property name="size" type="BannerAdSize" required>
  Represents the size of a banner ad.
</Property>

---

<Property name="maxWidth" type="number" optional>
  Maximum width for banner ad. Defaults to screen width.
</Property>

---

<Property name="maxHeight" type="number" optional>
  Maximum height for banner ad. Defaults to screen height.
</Property>
---

<Property name="autoReload" type="boolean" optional>
  If enabled, the ad will automatically retry loading the ad if an error occurs during the loading process. By default enabled.
</Property>

---

<Property name="refreshInterval" type="number" optional>
  Sets the refresh interval in seconds for displaying ads. Set `0` to disable automatic refreshing. 
  This automatic refresh worksregardless of the `autoReload` setting. By default 30 seconds.
</Property>

---

<Property name="placement" type="string" optional>
  An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.
</Property>

---

<Property name="casId" type="string" optional>
  The unique identifier of the CAS content for each platform. Leave undefined to use the initialization identifier.
</Property>

---

<Property name="onAdViewLoaded" type="(info: AdViewInfo) => void" optional>
  Callback to be invoked when the ad content has been successfully loaded.
</Property>

---

<Property name="onAdViewFailed" type="(error: AdError) => void" optional>
  Callback to be invoked when the ad content fails to load.
</Property>

---

<Property name="onAdViewClicked" type="() => void" optional>
  Callback to be invoked when the ad content is clicked by the user.
</Property>

---

<Property name="onAdViewImpression" type="(info: AdContentInfo) => void" optional>
  Callback to be invoked when an ad is estimated to have earned money.
</Property>

## Complete example
- [Adaptive banner ad example](https://github.com/cleveradssolutions/CAS-ReactNative/blob/main/example/src/AdaptiveBannerExample.tsx)
- [Standard banner ad example](https://github.com/cleveradssolutions/CAS-ReactNative/blob/main/example/src/BannerExample.tsx)
- [Multi banners ad example](https://github.com/cleveradssolutions/CAS-ReactNative/blob/main/example/src/ScrolledAdViewExample.tsx)
```

### Enabling test ads

Source: https://production.docs.page/docs/reactnative/enabling-test-ads

```mdx

It's important to enable test ads during development so that you can click on them without charging CAS advertisers.

<Error>  
We strongly suggest that you enable test ads mode when you validate the integration. If you click on too many ads without being in test mode, you risk your account being flagged for invalid activity.  
</Error>  

There are two ways to get test ads:
- [Enable test ad mode](reactnative/enabling-test-ads#enable-test-ad-mode) for all devices.
- [Set device ids to test ad](reactnative/enabling-test-ads#enable-test-devices).

Ads with Test Ads mode are safe to click. Requests, impressions, and clicks on test ads will not show up in your account's reports.
Test full-screen ads displays details of CAS integration and tips for solving errors. Go to the Mediation Adapters section to make sure that the advertising networks you want are integrated correctly.

<Image height="500" alt="image" src="/assets/Enabling-test-ads-1.jpg" />  
<Image height="500" alt="image" src="/assets/Enabling-test-ads-2.jpg" />  

## Enable Debug log mode
The enabled Debug Mode will display a lot of useful information for debugging about the states of the SDK with log tag `CAS`.
Disabled by default. Disabling Debug Mode may improve application performance.
```ts
CASMobileAds.setDebugLoggingEnabled(true);
```

<Info>  
If you have discovered the problem in the work of the SDK, please provide us with a description of the problem along with the full log of your device.  
</Info>  

## Enable test ad mode
The quickest way to enable testing is to use test ad mode. The test ad mode are not associated with your CAS account, so there's no risk of your account generating invalid traffic when using these test ad mode.
The easiest way to load test ads is to use:

```ts
CASMobileAds.initialize(casId, {
  forceTestAds: __DEV__, // [!code highlight]
});
```

## Enable test devices
If you want to do more rigorous testing with production-looking ads, you can now configure your device as a test device and use your own manager id. Test devices can either be added programmatically.

Follow the steps below to add your device as a test device.

1. Run an app configured with the CAS on device.
2. Check the logcat output for a message that looks like this:

```
To get test ads on this device, set "12345678901234567890123456789012"
```

3. Copy your alphanumeric test device ID to your clipboard.
4. Modify your code to set the test device ID through add `TestDeviceIDs` before CAS manager initialize.

```ts
CASMobileAds.initialize(casId, {
  testDeviceIds: ['12345678901234567890123456789012'],
});
```

<Info>  
Be sure to remove the code that sets these test devices before you release your app.  
</Info>  

5. Re-run your app.
6. Well done, ads on this device are safe to click. Requests, impressions, and clicks on ads in test mode will not show up in your account's reports.
```

### Impression Level Data

Source: https://production.docs.page/docs/reactnative/impression-level-data

```mdx

CAS.AI SDK enables you to access detailed information for each impression through the impression callback APIs.  
The data includes which demand source served the ad and the exact or estimated revenue associated with it.  
This allows you to analyze and optimize your monetization and user acquisition strategies.

### AdContentInfo
The `AdContentInfo` structure contains information about a displayed ad.  
In React Native, this object is provided to the `AdImpressionEvent` for each ad format.

<Property name="format" type="string">
  The format of the ad that is shown. (e.g. `Banner`, `MREC`, `Interstitial`, `Rewarded`, `AppOpen`).
</Property>

---

<Property name="sourceName" type="string">
  The display name of the mediated network that purchased the impression.
</Property>

---

<Property name="sourceUnitId" type="string">
  The Ad Unit ID from the mediated network that purchased the impression.
</Property>

---

<Property name="creativeId" type="string" optional>
  The Creative ID associated with the ad, if available.
  You can use this ID to report creative issues to the Ad review team. 
</Property>

---

<Property name="revenue" type="number">
  The revenue generated from the impression, in USD. 
  The revenue value may be either estimated or exact, depending on the precision specified by `revenuePrecision`. 
</Property>

---

<Property name="revenuePrecision" type="string">
  The precision type of the revenue field. (e.g. `estimated`, `precise`, `floor`).
</Property>

---

<Property name="revenueTotal" type="number">
  The accumulated value of user ad revenue in USD from all ad format impressions. 
</Property>

---

<Property name="impressionDepth" type="number">
  The total number of impressions across all ad formats for the current user, across all sessions. 
</Property>


### Ad Impression callback

Each ad format exposes an impression callback with `AdContentInfo` details:

```ts
import {
  AppOpenAd,
  InterstitialAd,
  RewardedAd,
  type AdContentInfo,
} from 'react-native-cas';

function setAdImpressionCallbacks() {
  const unAppOpen = AppOpenAd.addAdImpressionEventListener(onAdImpression);
  const unInterstitial = InterstitialAd.addAdImpressionEventListener(onAdImpression);
  const unRewarded = RewardedAd.addAdImpressionEventListener(onAdImpression);

  return () => {
    unAppOpen();
    unInterstitial();
    unRewarded();
  };
}

function onAdImpression(impression: AdContentInfo) {
  // Called when an ad impression occurs.  
  const adPlatform = 'CAS';
  const adFormat = impression.format;
  const adSource = impression.sourceName;
  const adUnitName = impression.sourceUnitId;
  const value = impression.revenue;
  // All CAS revenue is sent in USD  
  const currency = 'USD';
}
```

For banners, attach the handler directly to the React component:

```tsx
<BannerAdView onAdViewImpression={(info) => onAdImpression(info)} />
```

### User ad summary
CAS tracks cumulative impression and revenue metrics that are included in each `AdContentInfo` payload:

```ts
const totalImpressions = impression.impressionDepth;
const totalRevenue = impression.revenueTotal;
```

<Info>
These counters persist between app sessions until the user clears your app’s data.
</Info>

## Automatic ad revenue collection
The CAS SDK have features to automatically collect ad revenue to Google Analytics and Tenjin Analytics. 
Contact your account manager for details of enabling automatic events.

### Google Analytics
To measure ad revenue with Google Analytics:

<Steps>
<Step>
Get started with [Firebase Analytics](https://firebase.google.com/docs/analytics/get-started).
</Step>
<Step>
Link your Firebase project to a Google Analytics account.
</Step>
</Steps>


The SDK automatically logs [`ad_impression`](https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#public-static-final-string-ad_impression)
events whenever an ad is displayed.
Events include parameters such as ad platform, source, currency, and value.
Alternatively, CAS may log the event as `CAS_Impression`.

### Tenjin
To measure ad revenue with Tenjin Analytics:

<Steps>
<Step>
Integrate the [Tenjin SDK](https://github.com/tenjin/tenjin-react-native-sdk).
</Step>
<Step>
Ensure a Tenjin session is initialized, **or** pass your key to CAS SDK so it initializes Tenjin automatically:

```ts
CASMobileAds.initialize(casId, {
  mediationExtras: { tenjin_key: TENJIN_SDK_KEY },
});
```
</Step>
</Steps>
```

### Initialize CAS SDK

Source: https://production.docs.page/docs/reactnative/initialize-cas

```mdx

Before loading ads, initialize the CAS Mobile Ads SDK by calling `CASMobileAds.initialize(casId, options?)`. The call returns a `Promise<InitializationStatus>` that resolves when initialization completes.

The `casId` is a unique identifier for CAS content on each platform. You can use `demo` to force test-ads mode if you haven't registered a `casId` yet.

```ts
import { Platform } from 'react-native';
import CASMobileAds, { InitializationStatus, Audience, PrivacyGeography, ConsentFlowStatus } from 'react-native-cas';

function initCAS() {
  const casId = Platform.select({ ios: 'YOUR_CAS_ID_IOS', android: 'YOUR_CAS_ID_ANDROID' });
  CASMobileAds.initialize(casId, {
    ...
  }).then((status: InitializationStatus) => {
    if (status.error) {
      console.log(`CAS initialization failed: ${status.error}`);
    } else {
      console.log(`CAS initialized`);
    }
  });
}
```

If an error occurs, the SDK attempts automatic re-initialization internally. However, the returned `Promise` is not updated with later status changes; call `initialize()` again for the latest `InitializationStatus`.

<Error>
Do not initialize mediated ad SDKs yourself — CAS does that for you.  
Ignoring this will cause integration issues.
</Error>

### Initialization Status

<Property name="error" type="string" optional>
Initialization error or null if success.
</Property>

---

<Property name="countryCode" type="string" optional>
User Country code ISO 2 or null if not allowed.
</Property>

---

<Property name="isConsentRequired" type="boolean">
Indicates the privacy options button is required.
</Property>

---

<Property name="consentFlowStatus" type="ConsentFlowStatus">
Consent flow status code, check `ConsentFlowStatus` enum values.
</Property>

## Automatic user consent flow
To collect user consent for personal data, use the built-in **Consent Flow**. It shows a consent form automatically during initialization.

```ts
CASMobileAds.initialize(casId, {
  showConsentFormIfRequired: true, // [!code highlight]
  debugGeography: PrivacyGeography.EUROPEAN_ECONOMIC_AREA
}).then((status) => {
  if (status.consentFlowStatus === ConsentFlowStatus.OBTAINED) {
    console.log('CAS obtained user consent');
  }
});
```

Wait for the consent flow to complete before initializing third-party SDKs (MMPs, analytics), otherwise they may not have access to required identifiers.

<Info>
Read more about **Debug geography** on [CAS User Consent Flow](reactnative/user-consent-flow).
</Info>

## Always test with test ads
Enable test ads during development so you can interact with ads safely.

```ts
CASMobileAds.initialize(casId, {
  forceTestAds: __DEV__, // [!code highlight]
  testDeviceIds: ['YOUR_TEST_DEVICE_ID'], // [!code highlight]
});
```

For more on test ads, see [Enable test ads](reactnative/enabling-test-ads).

## Prohibition on Personal Information from Children
Mark apps as child-directed or COPPA-applicable in the CAS UI. If you know specific users are COPPA-applicable, set the audience:

```ts
CASMobileAds.initialize(casId, {
  targetAudience: Audience.NOT_CHILDREN, // [!code highlight]
});
```

If your app targets both children and older users, implement a **neutral age screen** to ensure COPPA compliance.

## (Optional) Retrieve the Version Number
To programmatically retrieve the SDK version number at runtime, CAS provides the following method:
```ts
const sdkVersion = await CASMobileAds.getSDKVersion();
```

## (Optional) Trial ad-free interval
Defines the time interval, in seconds, starting from the moment of the initial app installation, during which users can use the application without ads being displayed while still retaining access to the Rewarded Ads format. Within this interval, users enjoy privileged access to the application's features without intrusive advertisements.  

```ts
const secondsIn7Days = 604800;
CASMobileAds.setTrialAdFreeInterval(secondsIn7Days);
```

## Complete example
- [Initialize CASMobileAds example](https://github.com/cleveradssolutions/CAS-ReactNative/blob/main/example/src/SetupScreen.tsx#L38)
```

### Interstitial Ads

Source: https://production.docs.page/docs/reactnative/interstitial-ads

```mdx

Interstitial ads are full-screen ads that cover the interface of their host app.
They're typically displayed at natural transition points in the flow of an app, such as between screens.
When an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.

Interstitial Ad management in React code is handled through the `InterstitialAd` class which extends the shared fullscreen ad logic.
The interstitial ad is displayed as an overlay on top of all app content and cannot be added to the ReactNative component tree.

```ts
import { InterstitialAd } from 'react-native-cas';
```

Below is a diagram showing the ad lifecycle and how autoload affects it.

<Image zoom src="/assets/Lifecycle-Screen-Ad.png" alt="Diagram" height="500" />

## Load Ad
CAS provides an option to enable autoload to simplify your app logic. 
Before using the ad, you should decide whether to enable autoload, or manually manage each ad loading cycle in your code.

When autoload is enabled, a new ad will be automatically loaded after each display, and loading failures will trigger automatic retry attempts.
```ts
useEffect(() => {
  InterstitialAd.setAutoloadEnabled(true);
}, []);
```

Manual load mode is useful when you only need to show a single ad per app screen, and the screens change frequently.

When you want to manually control ad loading, use the `loadAd()` function.
```ts
useEffect(() => {
  InterstitialAd.loadAd();
}, []);
```

Ad content may take some time to load after creating an ad instance.
To ensure the ad displays instantly when needed, load the ad instance in advance.

Use the `addAdLoadedEventListener` event to be notified when the ad is ready for display.

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.

```ts
useEffect(() => {
  RewardedAd.setPlacement("BestPlace"); // [!code focus] 
}, []);
```

## Ad content callbacks
`InterstitialAd` has several optional callbacks for the ad lifecycle. These callbacks can be registered via event listeners.

```ts
useEffect(() => {
  const unsubscribeLoaded = InterstitialAd.addAdLoadedEventListener(() => {
    // Called when an ad is successfully loaded. 
    console.log('Loaded');
  });
  const unsubscribeFailedToLoad = InterstitialAd.addAdFailedToLoadEventListener((error) => {
    // Called when an ad load failed. 
    console.log('Load failed:', error);
  });
  const unsubscribeFailedToShow = InterstitialAd.addAdFailedToShowEventListener((error) => {
    // Called when the ad failed to show full screen content. 
    console.log('Failed to show:', error);
  });
  const unsubscribeShowed = InterstitialAd.addAdShowedEventListener(() => {
    // Called when the ad showed the full screen content.
    console.log('Showed');
  });
  const unsubscribeClicked = InterstitialAd.addAdClickedEventListener(() => {
    // Called when a click is recorded for an ad.
    console.log('Clicked');
  });
  const unsubscribeImpression = InterstitialAd.addAdImpressionEventListener((info: AdContentInfo) => {
    // Called when an impression occurs on the ad. 
    console.log('Impression', info);
  });
  const unsubscribeDismissed = InterstitialAd.addAdDismissedEventListener(() => {
    // Called when the ad dismissed full screen content. 
    console.log('Dismissed');
  });

  return () => {
    unsubscribeLoaded();
    unsubscribeFailedToLoad();
    unsubscribeFailedToShow();
    unsubscribeShowed();
    unsubscribeImpression();
    unsubscribeClicked();
    unsubscribeDismissed();
  };
}, []);
```

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](reactnative/impression-level-data).  
- When an error occurs during ad impression, only `AdFailedToShowEvent` is triggered.  
  In this case, `AdDismissedEvent` will not be executed since the impression is not considered successful.
</Info>

## Show Ad
Interstitial ads should be displayed during natural pauses in the flow of an app. Between app screens is a good example, or after the user completes a task.

You can choose when to show the ad by calling:

```ts
InterstitialAd.showAd();
```

If the ad is not ready at that moment, the `AdFailedToShowEvent` will be triggered with a reason.

You have the option to check `isLoaded()` if it's required by your app's logic.

```ts
const isAdLoaded = await InterstitialAd.isAdLoaded();
```

### Auto Show Ad mode
CAS provides the option to automatically show a loaded ad when the user returns to the app. 

To enable this behavior, set autoshow enabled:

```ts
InterstitialAd.setAutoshowEnabled(true);
```

## Minimum interval between impressions
The minimum interval between showing interstitial ads, in seconds.  
Attempting to show a new interstitial ad before the interval has passed after the previous one was dismissed will trigger `AdFailedToShowEvent` with `AdErrorCode.NOT_PASSED_INTERVAL`.

```ts
InterstitialAd.setMinInterval(0); // [!code highlight]
```

Note that the timer for the minimum interval is shared across all interstitial ad instances, but the minimum interval value may differ for each ad instance.

If you need to reset the minimum interval timer after showing a Rewarded Ad or an AppOpen Ad, you can call the `InterstitialAd.restartInterval()` method in the dismissal flow of those ad formats.

## Mute Ad sounds
Indicates if the application’s audio is muted. Affects initial mute state for fullscreen ads. Use this method only if your application has its own volume controls (e.g., custom music or sound effect muting).

```ts
CASMobileAds.setAdSoundsMuted(true);
```

Not muted by default.

## Release ad resource
Be sure to release ad resources when no longer needed:

```ts
useEffect(() => {
  return () => {
    InterstitialAd.destroy();
  };
}, []);
```

## Some best practices

#### Consider whether interstitial ads are the right type of ad for your app.
Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, like sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it's easy to present an interstitial ad without disrupting their experience. Make sure you consider at which points in your app's workflow you'll display interstitial ads and how the user is likely to respond.

#### Remember to pause the action when displaying an interstitial ad.
There are a number of different types of interstitial ads: text, image, video, and more. It's important to make sure that when your app displays an interstitial ad, it also suspends its use of some resources to allow the ad to take advantage of them. For example, when you make the call to display an interstitial ad, be sure to pause any audio output being produced by your app.

#### Allow for adequate loading time.
Just as it's important to make sure you display interstitial ads at an appropriate time, it's also important to make sure the user doesn't have to wait for them to load. Loading the ad in advance by calling `loadAd()` before you intend to call `showAd()` can ensure that your app has a fully loaded interstitial ad at the ready when the time comes to display one.

#### Don't flood the user with ads.
While increasing the frequency of interstitial ads in your app might seem like a great way to increase revenue, it can also degrade the user experience and lower clickthrough rates. Make sure that users aren't so frequently interrupted that they're no longer able to enjoy the use of your app.

## Complete example
- [Interstitial ad example](https://github.com/cleveradssolutions/CAS-ReactNative/blob/main/example/src/InterstitialExample.tsx)
```

### Manual Native Ad

Source: https://production.docs.page/docs/reactnative/native-ad-manual

```mdx

To build a custom native ad layout, render `NativeAdView` **with children** and place asset views inside it.
Each asset view is a React Native component that binds to the underlying native ad.

```ts
import { NativeAdView } from 'react-native-cas';
```

## Asset views reference

| Component                   | Type           | Recommended | Description |
| --------------------------- | -------------- | ----------- | ----------- |
| `NativeAdView.AdChoices`    | View           | Yes         | AdChoices overlay icon. Place it in a visible corner (or reserve space for it).                                         |
| `NativeAdView.Media`        | View           | Yes         | Main media content (image or video). Use this instead of a regular `Image` when you need primary content.               |
| `NativeAdView.Headline`     | Text           | Yes         | The ad headline/title text.                                                                                             |
| `NativeAdView.CallToAction` | Text + overlay | If provided | Call-to-action element (e.g., “Install”, “Open”, “Learn more”). Includes an internal overlay view for correct tracking. |
| `NativeAdView.Icon`         | View           | If provided | App icon / advertiser logo (usually square 1:1).                                                                        |
| `NativeAdView.Body`         | Text           | Optional    | Main body text for the ad.                                                                                              |
| `NativeAdView.Advertiser`   | Text           | Optional    | Advertiser/brand name (commonly present for content ads).                                                               |
| `NativeAdView.Store`        | Text           | Optional    | Store name where the product is available.                                                                              |
| `NativeAdView.Price`        | Text           | Optional    | Price text for the advertised product/service.                                                                          |
| `NativeAdView.ReviewCount`  | Text           | Optional    | Review count for the app/product (if available).                                                                        |
| `NativeAdView.StarRating`   | View           | Optional    | Star rating visualization (if available).                                                                               |
| `NativeAdView.AdLabel`      | Text           | Optional    | Optional “Ad” label provided by the network/SDK (if available). You may also render your own static badge.              |

## Advertising requirements

- The ad view must be visible and non-transparent.
- Do not edit the text content of SDK-provided assets.
- Do not edit SDK-provided images.
- At a single point in time, a loaded native ad should be displayed in one view only.

<Info>
If you want a ready-to-use layout without manual assets, use [Native Ad templates](reactnative/native-ads-templates).
</Info>

## Display ad views
Below is a minimal example of a manual layout.

```tsx
import React from 'react';
import { View, Text } from 'react-native';
import { NativeAdView, type NativeAdContent } from 'react-native-cas';

export function NativeManualCard({ ad }: { ad: NativeAdContent }) {
  return (
    <View style={{ padding: 12 }}>
      <NativeAdView ad={ad} style={{ width: '100%' }}>
        <NativeAdView.AdChoices style={{ position: 'absolute', top: 8, right: 8 }} />

        <NativeAdView.Headline style={{ fontSize: 16, fontWeight: '600' }} />

        <View style={{ flexDirection: 'row', marginTop: 8, alignItems: 'center' }}>
          <NativeAdView.Icon style={{ width: 48, height: 48, borderRadius: 8 }} />
          <View style={{ marginLeft: 10, flex: 1 }}>
            <NativeAdView.Advertiser style={{ fontSize: 12, opacity: 0.8 }} />
            <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 2 }}>
              <NativeAdView.StarRating style={{ height: 12, width: 80 }} />
              <NativeAdView.ReviewCount style={{ marginLeft: 6, fontSize: 12, opacity: 0.8 }} />
            </View>
          </View>
        </View>

        <Text style={{ marginTop: 8, fontSize: 12, opacity: 0.7 }}>Ad</Text>

        <View style={{ marginTop: 8, width: '100%', height: 180 }}>
          <NativeAdView.Media style={{ width: '100%', height: '100%' }} />
        </View>

        <NativeAdView.Body style={{ marginTop: 8, fontSize: 14 }} />

        <View style={{ flexDirection: 'row', marginTop: 8, justifyContent: 'space-between' }}>
          <NativeAdView.Price style={{ fontSize: 12, opacity: 0.8 }} />
          <NativeAdView.Store style={{ fontSize: 12, opacity: 0.8 }} />
        </View>

        <NativeAdView.CallToAction style={{ marginTop: 10, paddingVertical: 10, paddingHorizontal: 14 }} />
      </NativeAdView>
    </View>
  );
}
```

<Info>
If an asset is not provided by the loaded ad, the corresponding asset component renders nothing.  
Design your layout so it doesn’t break when optional assets (Icon, StarRating, Price, Store, etc.) are missing.
</Info>

<Warning>
- Do not implement custom click handlers on top of the native ad content.
- Do not wrap `NativeAdView.CallToAction` with `Pressable` / `TouchableOpacity`.
- Clicks and impressions are tracked by the SDK through the provided asset views.
</Warning>
```

### Native Ads

Source: https://production.docs.page/docs/reactnative/native-ads

```mdx

Native ads are ad assets presented using UI components that match your app’s look and feel.
In React Native, a loaded native ad is represented by `NativeAdContent`.

Native Ad loading in **React Native** is handled through `NativeAdLoader` from **react-native-cas**:

```ts
import {
  NativeAdLoader,
  NativeAdContent,
  AdChoicesPlacement,
  AdError,
  AdContentInfo,
} from 'react-native-cas';
```

## Add ad event listeners

Subscribe to loader events before requesting ads.

```tsx
import { useEffect } from 'react';
import { 
  NativeAdLoader, 
  type NativeAdContent, 
  type AdError, 
  type AdContentInfo 
} from 'react-native-cas';

useEffect(() => {
  const unsubLoaded = NativeAdLoader.addAdLoadedEventListener((ad: NativeAdContent) => {
    console.log('Native Ad loaded', ad);
  });

  const unsubFailedToLoad = NativeAdLoader.addAdFailedToLoadEventListener((error: AdError) => {
    console.log('Native Ad failed to load', error);
  });

  const unsubImpression = NativeAdLoader.addAdImpressionEventListener((info: AdContentInfo) => {
    console.log('Native Ad impression', info);
  });

  const unsubClicked = NativeAdLoader.addAdClickedEventListener(() => {
    console.log('Native Ad clicked');
  });

  const unsubFailedToShow = NativeAdLoader.addAdFailedToShowEventListener((error: AdError) => {
    console.log('Native Ad failed to show', error);
  });

  return () => {
    unsubLoaded();
    unsubFailedToLoad();
    unsubImpression();
    unsubClicked();
    unsubFailedToShow();
  };
}, []);
```

<Info>
Read more about `AdContentInfo` in [Impression Level Data](reactnative/impression-level-data).
</Info>

## Load ad content
Load one Native Ad content using `loadAd()`. A successfully loaded ad is delivered through `AdLoadedEventListener`.

```tsx
const [nativeAd, setNativeAd] = useState<NativeAdContent | null>(null);

useEffect(() => {
  const unsubLoaded = NativeAdLoader.addAdLoadedEventListener((ad: NativeAdContent) => {
    setNativeAd(prev => {
      prev?.destroy();
      return ad;
    });
  });

  NativeAdLoader.loadAd();

  return () => {
    unsubLoaded();
    setNativeAd(prev => {
      prev?.destroy();
      return null;
    });
  };
}, []);
```

### Load multiple ads (optional)
Request multiple native ads by passing a larger number to `loadAds`.
Each loaded ad will be delivered via `AdLoadedEventListener` (potentially multiple times).

```tsx
const [queue, setQueue] = useState<NativeAdContent[]>([]);

useEffect(() => {
  const unsubLoaded = NativeAdLoader.addAdLoadedEventListener((ad: NativeAdContent) => {
    setQueue(prev => [...prev, ad]);
  });

  NativeAdLoader.loadAds(3);

  return () => {
    unsubLoaded();
    setQueue(prev => {
      prev.forEach(ad => ad.destroy());
      return [];
    });
  };
}, []);
```

### Autoload Ad mode
The `NativeAdLoader` does not have an autoload ad mode like other ad formats, so you need to implement error handling and ad reloading manually.

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.

```ts
NativeAdLoader.setPlacement("BestPlace");
```

### StartVideoMuted
Controls whether native video content starts muted. Muted by default.
```ts
NativeAdLoader.setStartVideoMuted(true);
```

### AdChoicesPlacement
Preferred placement for the AdChoices icon inside your native ad view. Leave space in your preferred corner of your native ad view for the automatically inserted AdChoices logo. Available values: `TOP_LEFT`, `TOP_RIGHT`, `BOTTOM_RIGHT`, `BOTTOM_LEFT`. 
```ts
NativeAdLoader.setAdChoicesPlacement(AdChoicesPlacement.TOP_RIGHT);
```
By default the AdChoices icon position is set to the top right.
An AdChoices overlay can be added by the SDK if `NativeAdView.AdChoices` not used. 

<Info>
Google Ads does not support `NativeAdView.AdChoices` manual placement. Instead, specify the desired `AdChoicesPlacement` for the logo. Other ad sources will display their logo in your custom view.
</Info>

## Validate Ad Content (Optional)
Native ads can be preloaded and cached to reduce latency when displaying ads to users. However, these ads have a limited lifespan and may expire after a certain period. To ensure a seamless user experience, you should validate the ad content before displaying it.

Use the `NativeAdContent.isExpired` method to check if the ad has expired. If you attempt to display an expired ad, it will trigger an `AdFailedToShowEventListener`.

```ts
const isAdExpired = await ad.isExpired();
if (isAdExpired) {
  NativeAdLoader.loadAd();
  return;
}
```

If you display the ad immediately in `AdLoadedEventListener`, there's no need to check its validity, as it is guaranteed to be fresh at that moment.

## Display ad content

Native ad content is displayed using `NativeAdView`. There are two approaches:
- [Native Ad templates](reactnative/native-ads-templates) is quickest way to display native ads (render `NativeAdView` without children).
- [Manual Native Ad](reactnative/native-ad-manual) is fully custom layout using asset components inside `NativeAdView`.

## Release ad resources
Always release a loaded native ad when it is no longer displayed.

```ts
nativeAd.destroy();
```

You can also validate an ad before displaying it:

```ts
const expired = await nativeAd.isExpired();
if (expired) nativeAd.destroy();
```

<Warning>
- Do not display the same `NativeAdContent` in multiple views at the same time.  
- Always call `destroy()` when the ad is no longer used.
</Warning>


## Samples
- [Native ad example](https://github.com/cleveradssolutions/CAS-ReactNative/blob/main/example/src/NativeAdExample.tsx)
- [Native ad template size example](https://github.com/cleveradssolutions/CAS-ReactNative/blob/main/example/src/NativeTemplateSizeExample.tsx)
```

### Native Ad templates

Source: https://production.docs.page/docs/reactnative/native-ads-templates

```mdx

Native templates are the fastest way to display native ads.
To use a template, render `NativeAdView` **without children**.
The native SDK will build the layout and populate it automatically.

```ts
import { NativeAdView, NativeAdContent, NativeTemplateStyle } from 'react-native-cas';
```

## Template layouts

The template layout depends on the `NativeAdView` size (mainly height).

1. If the height is greater than 500, a large native ad layout is used.

   <Image height="500" alt="Large native template" src="/assets/Native-Template-Screen.jpg" />

2. If the height is greater than 200, a medium layout is used.

   <Image width="300" alt="Medium native template" src="/assets/Native-Template-MRec.jpg" />

3. Otherwise, a small layout is used.

   <Image width="300" alt="Small native template" src="/assets/Native-Template-Small.jpg" />

## Display a template view

Provide a size for predictable layout (recommended).

```tsx
import React from 'react';
import { View } from 'react-native';
import { NativeAdView, NativeAdContent } from 'react-native-cas';

export function NativeTemplateCard({ ad }: { ad: NativeAdContent }) {
  return (
    <View style={{ width: '100%' }}>
      <NativeAdView ad={ad} width={300} height={250} />
    </View>
  );
}
```

<Warning>
- If you add any children to `NativeAdView`, the template mode is disabled and you must provide asset views manually.
- Keep the view mounted while it’s visible for smoother UX.
</Warning>

## Customize template style (optional)

You can customize the template appearance using `templateStyle`.

- The background color
- The primary color for Call-to-Action background
- The text color for Call-to-Action
- The Headline text color
- The Headline text font style
- The Secondary text color
- The Secondary text font style

```tsx
export function StyledTemplate({ ad }: { ad: NativeAdContent }) {
  return (
    <NativeAdView
      ad={ad}
      width={300}
      height={250}
      templateStyle={{
        backgroundColor: '#FFFFFF',
        primaryColor: '#3B82F6',
        primaryTextColor: '#FFFFFF',
        headlineTextColor: '#111827',
        headlineFontStyle: 'bold',
        secondaryTextColor: '#6B7280',
        secondaryFontStyle: 'normal',
      }}
    />
  );
}
```
```

### Rewarded Ads

Source: https://production.docs.page/docs/reactnative/rewarded-ads

```mdx

Rewarded ads let you offer users in-app items, such as continued gameplay, virtual currency, or other rewards, in exchange for their engagement with ads.
Rewarded ads boost engagement because users receive a tangible benefit for their time.

Rewarded Ad management in React code is handled through the `RewardedAd` class which extends the shared fullscreen ad logic.
The rewarded ad is displayed as an overlay on top of all app content and cannot be added to the ReactNative component tree.

```ts
import { RewardedAd } from 'react-native-cas';
```

Below is a diagram showing the ad lifecycle and how autoload affects it.

<Image zoom src="/assets/Lifecycle-Rewarded-Ad.png" alt="Diagram" height="500" />

## Load Ad
CAS provides an option to enable autoload to simplify your app logic. 
Before using the ad, you should decide whether to enable autoload, or manually manage each ad loading cycle in your code.

When autoload is enabled, a new ad will be automatically loaded after each display, and loading failures will trigger automatic retry attempts.
```ts
useEffect(() => {
  RewardedAd.setAutoloadEnabled(true);
}, []);
```

Manual load mode is useful when you only need to show a single ad per app screen, and the screens change frequently.

When you want to manually control ad loading, use the `loadAd()` function.
```ts
useEffect(() => {
  RewardedAd.loadAd();
}, []);
```

Ad content may take some time to load after creating an ad instance.
To ensure the ad displays instantly when needed, load the ad instance in advance.

Use the `addAdLoadedEventListener` event to be notified when the ad is ready for display.

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.

```ts
useEffect(() => {
  RewardedAd.setPlacement("BestPlace"); // [!code focus] 
}, []);
```

## Ad content callbacks
`RewardedAd` provides several lifecycle event listeners to handle ad behavior:

```ts
useEffect(() => {
  const unsubscribeReward = RewardedAd.addAdUserEarnRewardEventListener(() => {
    // Called when the user has earned the reward.
    console.log('Reward the user for watching the ad');
  });
  const unsubscribeLoaded = RewardedAd.addAdLoadedEventListener(() => {
    // Called when an ad is successfully loaded. 
    console.log('Loaded');
  });
  const unsubscribeFailedToLoad = RewardedAd.addAdFailedToLoadEventListener((error) => {
    // Called when an ad load failed. 
    console.log('Load failed:', error);
  });
  const unsubscribeFailedToShow = RewardedAd.addAdFailedToShowEventListener((error) => {
    // Called when the ad failed to show full screen content. 
    console.log('Failed to show:', error);
  });
  const unsubscribeShowed = RewardedAd.addAdShowedEventListener(() => {
    // Called when the ad showed the full screen content.
    console.log('Showed');
  });
  const unsubscribeClicked = RewardedAd.addAdClickedEventListener(() => {
    // Called when a click is recorded for an ad.
    console.log('Clicked');
  });
  const unsubscribeImpression = RewardedAd.addAdImpressionEventListener((info: AdContentInfo) => {
    // Called when an impression occurs on the ad. 
    console.log('Impression', info);
  });
  const unsubscribeDismissed = RewardedAd.addAdDismissedEventListener(() => {
    // Called when the ad dismissed full screen content. 
    console.log('Dismissed');
  });

  return () => {
    unsubscribeReward();
    unsubscribeLoaded();
    unsubscribeFailedToLoad();
    unsubscribeFailedToShow();
    unsubscribeShowed();
    unsubscribeClicked();
    unsubscribeImpression();
    unsubscribeDismissed();
  };
}, []);
```

<Info>
- Read more about `AdContentInfo` structure in [Impression Level Data](reactnative/impression-level-data).  
- When an error occurs during ad impression, only `AdFailedToShowEvent` is triggered.  
  In this case, `AdDismissedEvent` will not be executed since the impression is not considered successful.
</Info>

## Show Ad
Be sure to `addAdUserEarnRewardEventListener` and reward the user for watching an ad.  

You can choose when to show the ad by calling `show()`:
```ts
RewardedAd.showAd();
```

The `AdUserEarnRewardEvent` differs from `AdDismissedEvent` — the user might not complete the ad and thus not earn a reward.

If the ad is not ready at that moment, the `AdFailedToShowEvent` will be triggered with a reason provided in the `AdError`.

You have the option to check `isAdLoaded()` if it's required by your app's logic.
```ts
const isAdLoaded = await RewardedAd.isAdLoaded();
```

## Extra fill by Interstitial Ad
CAS provides the option to load the interstitial ads as a fallback when a rewarded video ad has no available fill. 
Interstitial ads do not require the user to watch the entire ad to completion. 
However, the `AdUserEarnRewardEvent` will still be triggered as if the user completed the rewarded video.

```ts
RewardedAd.setExtraFillByInterstitialAd(true); // [!code highlight]
```

## Mute Ad sounds
Indicates if the application’s audio is muted. Affects initial mute state for fullscreen ads. Use this method only if your application has its own volume controls (e.g., custom music or sound effect muting).

```ts
CASMobileAds.setAdSoundsMuted(true);
```

Not muted by default.

## Release ad resource
Be sure to release ad resources when no longer needed:

```ts
useEffect(() => {
  return () => {
    RewardedAd.destroy();
  };
}, []);
```

## Complete example
- [Rewarded ad example](https://github.com/cleveradssolutions/CAS-ReactNative/blob/main/example/src/RewardedExample.tsx)
```

### Targeting options

Source: https://production.docs.page/docs/reactnative/targeting-options

```mdx

You can now easily tailor the way you serve your ads to fit a specific audience!
You’ll need to inform our servers of the users’ details so the SDK will know to serve ads according
to the segment the user belongs to.

### User Age
Set user age. Limitation: 1-99. By default 0 is 'unknown'.

```ts
CASMobileAds.setUserAge(12);
```

### User Gender

Set targeting to user’s gender. Limitation: `unknown, male, female`.

```ts
CASMobileAds.setUserGender(Gender.MALE);
``` 

### User Location auto collection
Collect from the device the latitude and longitude coordinated truncated to the hundredths decimal place.

* Collect only if your application already has the relevant end-user permissions.
- Does not collect if the target audience is children.
- Disabled by default.

```ts
CASMobileAds.setLocationCollectionEnabled(true);
```

### App Keywords
Set a list of keywords, interests, or intents related to your application. Words or phrases describe
the current activity of the user for targeting purposes.

```ts
CASMobileAds.setAppKeywords(keywords);
```

### App Content URL

Set the content URL for a website whose content matches the app's primary content. This website content is used for targeting and brand safety purposes. Limitation: max URL length 512.

```ts
CASMobileAds.setAppContentUrl(contentUrl);
```
```

### User Consent Flow

Source: https://production.docs.page/docs/reactnative/user-consent-flow

```mdx

<Info>
It is optional to use the CMP flow included with the CAS SDK. If you integrate your own CMP flow, make sure that flow completes before you initialize the CAS SDK.
</Info>

<Info>
If you implement a CMP that is compliant with IAB TCF v2 ([Transparency & Consent Framework](https://iabeurope.eu/tcf-2-0/)) for your user consent flow, the CAS SDK supports sending the TCF v2 consent to networks. In this case, the CAS Consent Flow will not be shown to the user.
</Info>

In order for CAS and our ad providers to deliver ads that are more relevant to your users, as a mobile app publisher, you need to collect explicit user consent for use of personal data in the regions covered by GDPR, CCPA, LGPD, PIPEDA.

### 1. Opt-in consent for the collection and use of personal data in the regions covered by GDPR, CCPA, LGPD, PIPEDA.
Any businesses established are required to comply with GDPR in Europe, CCPA in California, LGPD in Brazil, PIPEDA in Canada or risk facing heavy fines.

Keep in mind that it’s best to contact qualified legal professionals, if you haven’t done so already, to get more information and be well-prepared for compliance.

Read more about:

* GDPR - [General Data Protection Regulation](https://gdpr-info.eu)
* CCPA - [The California Consumer Privacy Act](https://theccpa.org)
* LGPD - [General Personal Data Protection Act](https://lgpd-brazil.info)
* PIPEDA - [The Personal Information Protection and Electronic Documents Act](https://www.priv.gc.ca/en/privacy-topics/privacy-laws-in-canada/the-personal-information-protection-and-electronic-documents-act-pipeda/)

<Image height="400" alt="image" src="/assets/User-Consent-Flow-1.png" />

#### Users will not see the Consent dialog if at least one of following is true
* Users located in regions that are not covered by information protection
* Users who are subject to COPPA restrictions.

### 2. Asking user permission to track them or access their device’s advertising identifier
With iOS 14.5 and later, you need to receive the user’s permission through the `AppTrackingTransparency` framework in order to track them or access their device’s advertising identifier.  Read more about Asking Permission to Track and AppTrackingTransparency Framework on [Apple developer page](https://developer.apple.com/app-store/user-privacy-and-data-use/)

<Warning>  
If an app does not present this request, the IDFA will automatically be zeroed out, which may lead to a significant loss in ad revenue.
</Warning>

#### Users will not see the ATT request if at least one of the following is true
* Users using iOS versions below 14.5
* Users who have indicated that they do not allow apps to ask to track them, by setting *Settings > Privacy, Allow Apps to Request to Track*
* Users with child accounts, or who are under age 18, who are signed in via their Apple ID
* Users who have already answered so far
* The app does not have a usage tracking description in **Info.plist** under `NSUserTrackingUsageDescription` key

## Automatic consent flow
The automatic consent flow is enabled by default and described on the [CAS initialization page](reactnative/initialize-cas).

## Manual consent flow
Call `CASMobileAds.showConsentFlow()` to show the built-in consent form manually.  If the consent is required, the SDK loads the form and immediately presents it.  

The `Promise<ConsentFlowStatus>` completes after the form is dismissed.  If consent is not required, the `Promise` resolves instantly.


```ts
import CASMobileAds, { ConsentFlowStatus } from 'react-native-cas';

CASMobileAds.showConsentFlow().then((status) => {
  if (status === ConsentFlowStatus.OBTAINED) {
    // User consent obtained.
  }
});
```

| ConsentFlow constant   | Description                                                        |
| ---------------------- | ------------------------------------------------------------------ |
| OBTAINED               | User consent obtained. Personalized vs non-personalized undefined. |
| NOT_REQUIRED           | User consent not required.                                         |
| UNAVAILABLE            | User consent unavailable.                                          |
| INTERNAL_ERROR         | There was an internal error.                                       |
| NETWORK_ERROR          | There was an error loading data from the network.                  |
| STILL_PRESENTING       | There was an error with another form is still being displayed.     |

<Warning>  
The cache consent status on your app or a previously saved consent string, could lead to a [TCF 3.3](https://support.google.com/admanager/answer/9999955) error if consent is expired.
</Warning>

## Privacy options button
Some consent forms require the user to modify their consent at any time. Adhere to the following steps to implement a privacy options button if required.

1. Implement a UI element, such as a button in your app's settings page, that can trigger a privacy options form.
2. Once `initialize()` completes, check `isConsentObtained` to determine whether to display the UI element that can present the privacy options form.
3. When a user interacts with your UI element, call `show()` to show the form so the user can update their privacy options at any time.

```ts
import CASMobileAds, { ConsentFlowStatus } from 'react-native-cas';

var isConsentObtained = false;

function initialize() {
  CASMobileAds.initialize(casId, {
    showConsentFormIfRequired: true,
  }).then((status) => {
    isConsentObtained = status.consentFlowStatus === ConsentFlowStatus.OBTAINED; // [!code highlight]
  });
}

function showPrivacyOptionsForm() {
  CASMobileAds.showConsentFlow().then((status) => {
    isConsentObtained = status === ConsentFlowStatus.OBTAINED;
  });
}
```

## Debug geography
The SDK provides a way to test your app's behavior as though the device was located in the EEA or UK using the `PrivacyGeography` enum.
Specify it in the SDK initialization arguments, and the setting will be applied only for test sessions.

```ts
import { CASMobileAds, PrivacyGeography } from 'react-native-cas';

CASMobileAds.initialize(casId, {
  forceTestAds: __DEV__,
  debugGeography: PrivacyGeography.EUROPEAN_ECONOMIC_AREA, // [!code highlight]
});

```

## Meta Audience Network Data Processing Options for Users in California
The CAS does not support your handling of CCPA opt-out values for Meta Audience Network, you must work directly with the network to purposes of your obligations for CCPA compliance.

To learn how to implement Meta Audience Network’s “Limited Data Use” flag, read the [Additional Meta AudienceNetwork steps](reactnative/additional-meta-audiencenetwork-steps).
```

### Additional Meta AudienceNetwork steps

Source: https://production.docs.page/docs/unity/additional-meta-audiencenetwork-steps

```mdx

## Data Processing Options for US Users
Meta Audience Network Data Processing Options for US Users Limited Data Use is a data processing option that gives you more control over how your data is used in Meta’s systems and better supports your compliance efforts with various US state privacy regulations. To utilize this feature, you must proactively enable Limited Data Use.  
Visit [Meta’s developer documentation](https://developers.facebook.com/docs/marketing-apis/data-processing-options) for details.

CAS provide an alternative way of pass `FBAdSettings.setDataProcessingOptions` flags using `MediationExtras.facebookDataProcessing` with values:
- `""` to explicitly not enable Limited Data Use (LDU) mode
- `"LDU"` to enable LDU mode using geolocation
- `"LDU_1_1000"` to enable LDU for users and specify user geography  

Define LDU flag in CAS manager builder before initialization:
```cs
CAS.MobileAds.BuildManager()
    .WithMediationExtras(MediationExtras.facebookDataProcessing, "LDU")
    ... //Other parameters
    .Initialize();
```
## iOS Advertising Tracking Enabled for Audience Network
Implement the [setAdvertiserTrackingEnabled](https://developers.facebook.com/docs/audience-network/setting-up/platform-setup/ios/advertising-tracking-enabled) flag, irrespective of the use of mediation, to inform Meta whether to use the data to deliver personalized ads.  
CAS provide an alternative way of pass `FBAdSettings.setAdvertiserTrackingEnabled` flags using `MediationExtras.facebookAdvertiserTracking`.  
- Value `"1"` flag to inform Audience Network to use the data to deliver personalized ads in line with your own legal obligations, platform terms, and commitments you’ve made to your users.
- Value `"0"` flag to inform Audience Network to not be able to deliver personalized ads.
```cs
CAS.ATTrackingStatus.Request((status) => {
  CAS.MobileAds.BuildManager()
    .WithMediationExtras(MediationExtras.facebookAdvertiserTracking, isTrack ? "1" : "0")
    ... //Other parameters
    .Initialize();
});
```
<Info>
This functionality is for iOS only and will not have any effect on Android.
</Info>
```

### Affiliate program

Source: https://production.docs.page/docs/unity/affiliate-program

```mdx

## Add Firebase Analytics
Google Analytics collects usage and behavior data for your app.  
Add the [Firebase Unity SDK](https://firebase.google.com/docs/unity/setup#prerequisites) (specifically, `FirebaseAnalytics.unitypackage`) to your Unity project.

## Collect user loss analytics
To collect user loss analytics, you need to add the following script to the project.  
The script automatically sends the transition to a new scene.  
If your game has a single game scene, call a `UserProgressAnalytics.Send()` method with more information about the user's current progress.
```cs
using UnityEngine;
using UnityEngine.SceneManagement;
using Firebase.Analytics;

namespace CAS
{
  public static class UserProgressAnalytics
  {
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
    public static void Init()
    {
      SceneManager.activeSceneChanged += OnActiveSceneChanged;
    }

    private static void OnActiveSceneChanged(Scene current, Scene next)
    {
      Send(next.name);
    }

    public static void Send(string progress)
    {
      Parameter[] fParams = new Parameter[]
      {
        new Parameter(FirebaseAnalytics.ParameterScreenClass, "game.scene"),
        new Parameter(FirebaseAnalytics.ParameterScreenName, progress)
      }
      FirebaseAnalytics.LogEvent(FirebaseAnalytics.EventScreenView, fParams);
    }
  }
}
```
```

### App Open Ad object

Source: https://production.docs.page/docs/unity/app-open-ad-object

```mdx

App open ads are a special ad format intended for publishers wishing to monetize their app load screens. App open ads can be closed at any time, and are designed to be shown when your users bring your app to the foreground.  App open ads automatically show a small branding area so users know they're in your app.  

This guide explains how to integrate app open ads into a Unity app.

Pros compared to Interstitial ads:
- Much faster ad loading.
- End user-friendly interface.  

Cons:
- Only Google Ads (AdMob) is supported.

## Add an AppOpenAdObject to the scene
1. Add an GameObject to your scene using `GameObject > Create Empty` in the Unity Editor.
2. Add Component `CleverAdsSolutions/AppOpen Ad Object` in the inspector to new GameObject.
3. Select [Manager ID](unity/configuring-sdk#manager-ids) from settings asset for each runtime platform.
4. Invoke `Load()` method to load ad.
5. Invoke `Show()` method to show ad.  

<Image width="326" alt="image" src="/assets/unity/App-Open-Ad-object-1.png" />

- **Autoshow loaded Ad when user open the app**  
The ad will be shown when the user opens the app. Additionally, the ad must be loaded, and this component must not be destroyed.

## Load Ad callbacks
- **On Ad Loaded**  
The event is invoked when the ad has finished loading.
- **On Ad Failed To Load**  
The event is invoked when the ad fails to load. The Message parameter describes the type of failure that occurred.

## Content callbacks
- **On Ad Failed To Show**  
The event is invoked when the ad failed to show. The Message parameter describes the type of failure that occurred.
- **On Ad Shown**  
The event is invoked when the ad is shown.
- **On Ad Clicked**  
The event is invoked when the user clicks on the ad.
- **On Ad Impression**  
The event is invoked when the ad count impression with [Impression Level Data](unity/impression-level-data) and `AdMetaData`.
- **On Ad Closed**  
The event is invoked when the ad is closed.

## Unity Events sample
You can implement functions that correspond to ad callbacks. For example, if you want to handle when the app open ad fails to show:
1. Create a function compatible with the ad callback in custom component.
```c#
public void OnAppOpenAdFailedToShow(string reason) {
    Debug.Log("AppOpen ad failed to show: " + reason);
}
```
2. Attach the script which contains the above function to any GameObject in the scene.
3. Click the **+** button, then drag & drop the GameObject that you've attached the script to.
4. Select the function that you want to link to the ad callback. For the parameterized ad callbacks, select the function to accept the dynamic variable so you can get the parameter value from the SDK.

## Use AdObject from script
Get the interstitial ad instance from the script:
```c#
AppOpenAdObject appOpenAd = adObject.GetComponent<AppOpenAdObject>();
```
Load the ad:
```c#
appOpenAd.Load();
```
Show the ad:
```c#
appOpenAd.Show();
```

## Cold starts and loading screens
The documentation thus far assumes that you only show app open ads when users foreground your app when it is suspended in memory. "Cold starts" occur when your app is launched but was not previously suspended in memory.  

An example of a cold start is when a user opens your app for the first time. With cold starts, you won't have a previously loaded app open ad that's ready to be shown right away. The delay between when you request an ad and receive an ad back can create a situation where users are able to briefly use your app before being surprised by an out of context ad. This should be avoided because it is a bad user experience.  

The preferred way to use app open ads on cold starts is to use a loading screen to load your game or app assets, and to only show the ad from the loading screen. If your app has completed loading and has sent the user to the main content of your app, do not show the ad.  

<Info>
In order to continue loading app assets while the app open ad is being displayed, always load assets in a background thread.
</Info>

## Best practices
App open ads help you monetize your app's loading screen, when the app first launches and during app switches, but it's important to keep best practices in mind so that your users enjoy using your app. It's best to:
- Show your first app open ad after your users have used your app a few times.
- Show app open ads during times when your users would otherwise be waiting for your app to load.
- If you have a loading screen under the app open ad, and your loading screen completes loading before the ad is dismissed, you may want to dismiss your loading screen from the `OnAppOpenAdClosed` and  `OnAppOpenAdFailedToShow` events.
```

### App Open Ads

Source: https://production.docs.page/docs/unity/app-open-ads

```mdx

App open ads are a special ad format intended for publishers wishing to monetize their app load screens. App open ads can be closed at any time, and are designed to be shown when your users bring your app to the foreground.  App open ads automatically show a small branding area so users know they're in your app.  

This guide explains how to integrate app open ads into a Unity app.

Pros compared to Interstitial ads:
- Much faster ad loading.
- End user-friendly interface.  

Cons:
- Only Google Ads (AdMob) is supported.

## Ad events
To further customize the behavior of your ad, you can hook into a number of events in the ad's lifecycle: loading, opening, closing, and so on. Listen for these events by registering a delegate for the appropriate event, as shown below.

```csharp
manager.OnAppOpenAdLoaded += AdLoaded;
manager.OnAppOpenAdFailedToLoad += AdFailedToLoad;
manager.OnAppOpenAdShown += AdShown;
manager.OnAppOpenAdFailedToShow += AdFailedToShow;
manager.OnAppOpenAdClicked += AdClicked;
manager.OnAppOpenAdClosed += AdClosed;

void AdLoaded()
{
    Debug.Log("AppOpen ad loaded");
}
void AdFailedToLoad(AdError error)
{
    Debug.Log("AppOpen failed to load an ad with error: " + error.GetMessage());
}
void AdShown()
{
    Debug.Log("AppOpen ad full screen content opened");
}
void AdFailedToShow(string error)
{
    Debug.LogError("AppOpen ad failed to open full screen content: " + error);
}
void AdClicked()
{
    Debug.Log("AppOpen ad was clicked");
}
void AdClosed()
{
    Debug.Log("AppOpen ad full screen content closed");
}
```

<Info>
- When an error occurs during ad impression, executed the `OnAppOpenAdFailedToShow` only.  In this case the `OnAppOpenAdClosed` will not be executed, since the impression is not considered successful.
- If a user returns to your app after having left it by clicking on an app open ad (`OnAppOpenAdClicked`), it makes sure they're not presented with another app open ad.
</Info>

Read more about event `OnAppOpenAdImpression` with [Impression Level Data](unity/impression-level-data) and `AdMetaData`.  
## Load an ad
Use `AdType.AppOpen` parameter for load ad:
```c#
void LoadAd()
{
    manager.LoadAd(AdType.AppOpen);
}
```
The AppOpen Ad format does not support auto-load ads mode.

<Info>
Attempting to load a new ad from the `OnAppOpenAdFailedToLoad` event is strongly discouraged. If you must load an ad from `OnAppOpenAdFailedToLoad` event, limit ad load retries to avoid continuous failed ad requests in situations such as limited network connectivity.
</Info>

## Check the ad availability
You can ask for the ad availability directly by calling the following function:
```c#
bool adLoaded = manager.IsReadyAd(AdType.AppOpen);
```

Avoid using `IsReadyAd` every frame in `Update` or `Coroutine`; instead, subscribe to the `OnAppOpenAdLoaded` event. This method call the native SDK and can affect the performance of your game. 

You don't have to check `IsReadyAd` before showing an ad; instead, subscribe to the `OnAppOpenAdFailedToShow` event, which will be triggered if the ad isn't ready to show.

## Listen to app state events
To display ads to the user when they open the application, it's important for you to use `OnApplicationBackground` and `OnApplicationForeground` events that will be triggered every time the application switches between foreground or background mode.
```csharp
void Awake()
{
    // This is used to launch the loaded ad when user open the app
    CAS.MobileAds.OnApplicationForeground += ApplicationForeground;
}

void OnDestroy()
{
    // Always unlisten to events when complete.
    CAS.MobileAds.OnApplicationForeground -= ApplicationForeground;
}

void ApplicationForeground()
{
    // Show the Ad
}
```

<Info>
Note that the Android runtime triggers app state events not from the main Unity thread. However, you can call CAS plugin methods without leaving the current thread
</Info>

## Show the ad
Use `AdType.AppOpen` parameter to show loaded ad:
```c#
manager.ShowAd(AdType.AppOpen);
```

Once you’ve successfully call `ShowAd()`, you will have shown your user an App Open Ad.  
In the case you want to serve another App Open Ad, you must repeat `LoadAd()` to request an additional ad.

To prepare an app open ad for the next impression opportunity, preload the app open ad once the `OnAppOpenAdClosed` or `OnAppOpenAdFailedToShow` ad event is raised.
```c#
void AdClosed()
{
    Debug.Log("AppOpen ad full screen content closed");
    LoadAd();
}

void AdFailedToShow(string error)
{
    Debug.LogError("AppOpen ad failed to open full screen content: " + error);
    LoadAd();
}
```

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.
```cs
manager.ShowAd(AdType.AppOpen, "BestPlace");
```

## Cold starts and loading screens
The documentation thus far assumes that you only show app open ads when users foreground your app when it is suspended in memory. "Cold starts" occur when your app is launched but was not previously suspended in memory.  

An example of a cold start is when a user opens your app for the first time. With cold starts, you won't have a previously loaded app open ad that's ready to be shown right away. The delay between when you request an ad and receive an ad back can create a situation where users are able to briefly use your app before being surprised by an out of context ad. This should be avoided because it is a bad user experience.  

The preferred way to use app open ads on cold starts is to use a loading screen to load your game or app assets, and to only show the ad from the loading screen. If your app has completed loading and has sent the user to the main content of your app, do not show the ad.  

<Info>
In order to continue loading app assets while the app open ad is being displayed, always load assets in a background thread.
</Info>

## Best practices
App open ads help you monetize your app's loading screen, when the app first launches and during app switches, but it's important to keep best practices in mind so that your users enjoy using your app. It's best to:
- Show your first app open ad after your users have used your app a few times.
- Show app open ads during times when your users would otherwise be waiting for your app to load.
- If you have a loading screen under the app open ad, and your loading screen completes loading before the ad is dismissed, you may want to dismiss your loading screen from the `OnAppOpenAdClosed` and  `AdFailedToShow` events.
```

### App Return Ad

Source: https://production.docs.page/docs/unity/app-return-ad

```mdx

The Return Ads which is displayed once the user returns to your application after a certain period of time.  
To minimize the intrusiveness, short time periods are ignored.  
Return ads are disabled by default.

<Warning>  
- The Ad on Return to App is a regular Interstitial Ad. 
- Automatic display is only possible when using autoload Interstitial Ad. 
- The Ad will be displayed only if the Interstitial Ad is currently loaded. After displaying the Interstitial Ad, it will be necessary to load a new advertisement.
- The Ad will not be shown if the interval since the last closure of the Interstitial Ad has not elapsed.
- Do not activate this ad format if your application displays an AppOpen Ad when returning to the app.
</Warning>

### Enable the ad
If you want to enable the Return Ads, simply invoke the following method.
```c#
manager.SetAppReturnAdsEnabled(true);
```

### Ad events
To further customize the behavior of your ad, you can hook into a number of events in the ad's lifecycle: opening, closing, and so on. Listen for these events by registering a delegate for the appropriate event, as shown below.
```c#
// Executed when the ad is displayed.
manager.OnAppReturnAdShown += () => Debug.Log("App return ad shown");
// Executed when the ad is failed to display.
manager.OnAppReturnAdFailedToShow += (error) => Debug.LogError(error);
// Executed when the user clicks on an Ad.
manager.OnAppReturnAdClicked += () => Debug.Log("App return ad clicked");
// Executed when the ad is closed.
manager.OnAppReturnAdClosed += () => Debug.Log("App return ad closed");
```

<Info>
When an error occurs during ad impression, executed the `OnAppReturnAdFailedToShow` only.  In this case the `OnAppReturnAdClosed` will not be executed, since the impression is not considered successful.
</Info>

Read more about event `OnAppReturnAdImpression` with [Impression Level Data](unity/impression-level-data) and `AdMetaData`.  

### Skip next return
You can call this method when you intentionally redirect the user to another application (for example Google Play) and do not want them to see ads when they return to your application.
```c#
manager.SkipNextAppReturnAds()
```

### Disable the ad
When you no longer want to show ads to users after they return to the app, invoke the following method.
```c#
manager.SetAppReturnAdsEnabled(false);
```
```

### Banner Ad object

Source: https://production.docs.page/docs/unity/banner-ad-object

```mdx

This guide shows you how to integrate banner ads into a Unity app. In addition to code snippets and instructions, it also includes information about sizing banners properly.  

## Add an BannerAdObject to the scene
1. Add an GameObject to your scene using `GameObject > Create Empty` in the Unity Editor.
2. Add Component `CleverAdsSolutions/Banner Ad Object` in the inspector to new GameObject.
3. Select [Manager ID](unity/configuring-sdk#manager-ids) from settings asset for each runtime platform.
4. Select [Ad position](unity/banner-ads#ad-position)
5. Select [Ad size](unity/banner-ads#ad-size)
6. Invoke `gameObject.SetActive(true)` method to show the banner ad.  

![image](https://user-images.githubusercontent.com/22005013/111324084-1fee3d00-8673-11eb-94a2-6cd2b6d001fd.png)

<Info>
An BannerAdObject does not have any rendered components. Therefore, you can place the GameObject anywhere in the scene.
</Info>

## Load Ad callbacks
- **On Ad Loaded**  
The event is invoked when the banner ad has finished loading.
- **On Ad Failed To Load**  
The event is invoked when the banner ad fails to load. The Message parameter describes the type of failure that occurred.

## Content callbacks
- **On Ad Shown**  
The event is invoked when the banner ad is displayed.
- **On Ad Clicked**  
The event is invoked when the user clicks on the banner ad.
- **On Ad Hidden**  
The event is invoked when the banner ad is hidden from screen.

## Unity Events sample
You can implement functions that correspond to ad callbacks. For example, if you want to handle when a banner ad fails to load:
1. Create a function compatible with the ad callback in custom component.
```c#
public void OnBannerAdFailedToLoad(string reason) {
    Debug.Log("Banner ad failed to load: " + reason);
}
```
2. Attach the script which contains the above function to any GameObject in the scene.
3. Click the **+** button, then drag & drop the GameObject that you've attached the script to.
4. Select the function that you want to link to the ad callback. For the parameterized ad callbacks, select the function to accept the dynamic variable so you can get the parameter value from the SDK.

## Use BannerAdObject from script
Get the active banner ad instance from the script:
```c#
BannerAdObject activeBanner = BannerAdObject.Instance;
```
Show the banner ad on screen:
```c#
activeBanner.gameObject.SetActive(true);
```
Hide the banner ad from screen:
```c#
activeBanner.gameObject.SetActive(false);
```
Set the banner Ad position on screen:
```c#
activeBanner.SetAdPosition(AdPosition.TopCenter);
```
Set the banner ad size:
```c#
activeBanner.SetAdSize(AdSize.Adaptive);
```
Calculate the actual size of an ad banner in pixels on the screen:
```csharp
Rect rect = activeBanner.rectInPixels;
Vector2 adSizePixels = rect.size;
Vector2 adPositionInPixels = rect.position; 
```
```

### Banner Ads

Source: https://production.docs.page/docs/unity/banner-ads

```mdx

This guide shows you how to integrate banner ads from CAS into a Unity app. In addition to code snippets and instructions, it also includes information about sizing banners properly.  

Enable Banner Ads for your game in `Assets > CleverAdsSolutions > Settings` menu.

> For easier ads integration using the Unity Editor, try the new [BannerAdObject](unity/banner-ad-object).

## Ad size
To load a banner ad, you need to specify the ad size. To do this, choose one of the `AdSize` from the list below:
1. **Adaptive banner** ads have a fixed aspect ratio for the maximum screen width. The adaptive size calculates the optimal height for that width with an aspect ratio similar to 320x50.
```csharp
AdSize adSize = AdSize.AdaptiveBanner;
```
The width cannot be less than 300 density independent pixels and larger than 728 density independent pixels.  
2. **Adaptive Full Width Banner** ads are similar to `AdaptiveBanner`, but they can have a width greater than 728 pixels in landscape orientation.
```csharp
AdSize adSize = AdSize.AdaptiveFullWidth;
```
3. **Smart ad size** selects the optimal dimensions depending on the device type. For mobile devices, it returns 320x50, while for tablets, it returns 728x90. In the UI, these banners occupy the same amount of space regardless of device type.
```csharp
AdSize adSize = AdSize.SmartBanner;
```
4. **Medium Rectangle** has a fixed size of 300x250.
```csharp
AdSize adSize = AdSize.MediumRectangle;
```
5. **Leaderboard** has a fixed size of 728x90 and is allowed on tablets only.
```csharp
AdSize adSize = AdSize.Leaderboard;
```
6. **Standard banner** has a fixed size of 320x50 and is the minimum ad size.
```csharp
AdSize adSize = AdSize.Banner;
```

Get the ad view interface for specific `AdSize`:
```cs
IAdView adView = manager.GetAdView(adSize);
```

<Info>
If a view for specific size has already been created then a reference to it will be returned without creating a new one.  
</Info>


## Load an Ad
By default, the **auto-load ads mode is used** and a load method does not need to be called.  
Call manual load ad after `manager.GetAdView()` if you use `LoadingManagerMode.Manual` only.  
 
```cs
adView.Load();
```

Also you can use the load for cancel current impression and load next ad.

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements.

The placement name should be set before loading the ads. Maximum 100 characters allowed for the placement name.
```cs
adView.placement = "BestPlace";
adView.Load();
```

## Ad events
To further customize the behavior of your ad, you can hook into a number of events in the ad's lifecycle: loading, clicking, and so on. Listen for these events by registering a delegate for the appropriate event, as shown below.

```cs
void OnEnable()
{
    adView.OnLoaded += AdLoaded;
    adView.OnFailed += AdFailedToLoad;
    adView.OnClicked += AdClicked;
}

void OnDisable()
{
    adView.OnLoaded -= AdLoaded;
    adView.OnFailed -= AdFailedToLoad;
    adView.OnClicked -= AdClicked;
}

void AdLoaded()
{
    // Called when the ad loaded and ready to present.
    Debug.Log("Banner ad loaded");
}

void AdFailedToLoad(AdError error)
{
    // Сalled when an error occurred with the ad.
    Debug.Log("Banner failed to load an ad with error: " + error.GetMessage());
}

void AdClicked()
{
    // Called when the user clicks on the Ad.
    Debug.Log("Banner ad was clicked");
}
```
Read more about event `OnImpression` with [Impression Level Data](unity/impression-level-data) and `AdMetaData`.  

## Display the Ad
The newly created `AdView` has an **inactive state**.  
When you are ready to show the ad on the screen, simply call the following method:
```cs
adView.SetActive(true);
```
When you need to hide AdView from the user, just deactivate it:
```cs
adView.SetActive(false);
```

<Info>
You can change the banner's activity even if it is not ready to be shown yet. When the ad is ready, banner will shown automatically.
</Info>

## Ad position
The position where the banner ad should be placed. The `CAS.AdPosition` enum lists the valid ad position values.  By default, the banner ad is centered at the bottom.  

The table for all positions on the screen. Some position values ​​do not support offset on the X or Y axis, this can be seen in the table as (X, Y). 

|        | Left     | Center |    Right |
| ------ | -------- | :----: | -------: |
| Top    | TL(X, Y) | TC(Y)  | TR(X, Y) |
| Middle | ML(X)    | MC(-)  |    MR(X) |
| Bottom | BL(X, Y) | BC(Y)  | BR(X, Y) |

Use the `SetPosition(int, int, AdPosition)` to place AdView at the X and Y offset, where the origin is the selected  corner (AdPosition) of the screen. 

The coordinates on the screen are determined in Density-independent Pixels(DP):
```cs
adView.SetPosition(xOffsetInDP, yOffsetInDP, AdPosition.TopLeft);
```

The coordinates on the screen are determined in pixels:
 ```cs
adView.SetPositionPx(xOffsetInPx, yOffsetInPx, AdPosition.TopLeft);
```

To specify a position on the screen without offset, use the position property. 
```cs
adView.position = AdPosition.TopCenter;
```
This line is the same as calling `SetPosition(0, 0, AdPosition.TopCenter)`

## Rect in pixels
You can calculate the actual rect of the Ad Banner in pixels on the screen.
```cs
Rect rect = adView.rectInPixels;
Vector2 adSizePixels = rect.size;
Vector2 adPositionInPixels = rect.position; 
```
This value is buffered after calculation, feel free to check ad view rect each frame.  
The position on the screen is calculated with the addition of indents for the cutouts.

CAS plugin provides the ability to get the correct device screen scale value to convert Pixels to Density-independent Pixels(DP) and vice versa.
```c#
float scale = CAS.MobileAds.GetDeviceScreenScale();
float widthInDP = adSizePixels.x / scale;
float heightInDP = adSizePixels.y / scale;

float someValueInPixels = someValueInDP * scale;
```

## Ad Refresh rate
An ad unit’s automatic refresh rate (in seconds) determines how often a new ad request is generated for that ad unit.  
We recommended using refresh rate 30 seconds. However, you can choose any value you want longer than 10 seconds.  

<Info>
Ad requests should not be made when the device screen is turned off.  
</Info>

Change the banner automatic refresh rate using the following method:
```cs
adView.refreshInterval = refreshIntervalInSeconds;
```
Or disable automatic refresh ads with method:
```cs
adView.DisableRefresh();
```

## Free ad memory
If you no longer need the `AdView` with specific size, please call `IDisposable.Dispose()` to free memory.
```cs
adView.Dispose();
```
After calling `Dispose()`, you can use `GetAdView(AdSize)` method to create a new view.

## Ad Availability
You can ask for the ad availability directly by calling the following function:
```cs
bool bannerLoaded = adView.isReady;
```

<Warning>  
We don’t recommend waiting for `isReady` to change in an Update or Coroutine. This property call the native SDK and can affect the performance of your game. Subscribe to the `OnLoaded` event instead.
</Warning>

## Complete example
 - [HelloWorld example](https://github.com/cleveradssolutions/CAS-Unity-Sample/blob/master/Assets/SampleCSharp/CSharpSampleController.cs) — a minimal implementation of all ad formats
```

### CAS Publishing Hub

Source: https://production.docs.page/docs/unity/cas-publishing-hub-integration

```mdx

<Success>
**Integrate with an AI assistant (LLM)**

You can integrate CAS Publishing Hub with the help of an AI assistant (Claude, Cursor, GitHub Copilot, etc.). Give it the instruction file [cas-publishing-hub.md](https://github.com/cleveradssolutions/docs/blob/main/llm-guides/cas-publishing-hub.md) - attach it to the chat or share its link - and ask the assistant to follow it. The guide walks the assistant through the complete integration. If you prefer to do it yourself, follow the manual steps below.
</Success>

CAS Publishing Hub is a Unity installer that sets up the whole publishing SDK for you: CAS, Tenjin and Firebase Analytics. It registers the required packages, installs them and checks the configuration, so you don't need to edit `Packages/manifest.json` by hand. Follow the steps below in order.

<Warning>
If your project already contains its own advertising or mediation SDK, remove it before you start. It is not compatible with CAS.
</Warning>

## Install CAS Publishing Hub
Choose one of the following methods to import CAS Publishing Hub into your Unity project.
1. npm (scoped registry)
2. Add package from git URL

### (Option 1) npm (scoped registry)
1. Open the [package manager settings](https://docs.unity3d.com/Manual/class-PackageManager.html) by selecting the Unity menu option **Edit > Project Settings > Package Manager**.
2. Add CAS Publishing as a scoped registry to the Package Manager window:
```
Name: CAS Publishing
URL: https://npm.cas.ai/
Scopes: ai.cas
```
3. Open the [package manager menu](https://docs.unity3d.com/Manual/upm-ui-install.html) by selecting the Unity menu option **Window > Package Manager**.
4. Set the manager scope drop-down to select **My Registries**.

![image](https://docs.unity3d.com/uploads/Main/upm-ui-unityregistry.png)

5. Select the **CAS Publishing Hub** package (`ai.cas.installer`) from the package list.
6. Press **Install**.

### (Option 2) Add package from git URL
1. Open the [package manager menu](https://docs.unity3d.com/Manual/upm-ui-install.html) by selecting the Unity menu option **Window > Package Manager**.
2. Press the **plus (+)** drop-down to select **Add package from Git URL**.

![image](https://user-images.githubusercontent.com/22005013/135641554-c38422fa-995e-4e56-9c3a-a89a72172081.png)

3. Enter the CAS Publishing Hub Git URL in the text box and click **Add**:
```
https://github.com/cleveradssolutions/CAS-Publishing-Hub.git?path=/installer#1.1.0
```
The Git URL ends with the tag name after `#`.

<Info>
Check Prerequisites and Troubleshooting on [Install a package from a Git URL](https://docs.unity3d.com/Manual/upm-ui-giturl.html) page of Unity Documentation.
</Info>

When the package is installed, the setup wizard opens automatically. You can open it again at any time from `CAS Hub > Open Hub`.

## Run the setup wizard

### 1. Choose a platform and enter your CAS ID
Select the platform you are building for (`Android` or `iOS`) and enter your CAS ID. It is applied to the CAS settings automatically after the installation.

<Image width="650" alt="Welcome step of the CAS Publishing Hub wizard" src="/assets/unity/publishers/hub/Hub-Integration-Step-1.png" />

### 2. Install the components
Check the list of components and press `Install`. CAS Publishing Hub adds the packages to your project and imports the required plugins. No scene files are changed.

<Image width="650" alt="Ready to install step of the CAS Publishing Hub wizard" src="/assets/unity/publishers/hub/Hub-Integration-Step-2.png" />

### 3. Choose ad formats
Select the ad formats your app uses. At least one is required.

<Image width="650" alt="Placements step of the CAS Publishing Hub wizard" src="/assets/unity/publishers/hub/Hub-Integration-Step-3.png" />

<Info>
Tenjin is enabled automatically - it reports attribution and purchases, so there is nothing to configure for it here.
</Info>

### 4. Add the Firebase config file
Press [`Open Firebase Console`](https://console.firebase.google.com/) to download the configuration file of your app:
- Android: `google-services.json`
- iOS: `GoogleService-Info.plist`

Then add it to the wizard:
- Press `Click to choose a file` and select the file, or
- drag a file that is already in your project from the Project window into the wizard.

<Image width="650" alt="Firebase setup step of the CAS Publishing Hub wizard" src="/assets/unity/publishers/hub/Hub-Integration-Step-4.png" />

<Info>
Don't have a Firebase project yet? Create one and share the permissions first, following the [Firebase checklist](/unity/firebase-integration).
</Info>

### 5. Check the result
When the setup is complete, the wizard shows a checklist confirming that the CAS SDK and Firebase are ready.

<Image width="650" alt="Setup complete step of the CAS Publishing Hub wizard" src="/assets/unity/publishers/hub/Hub-Integration-Step-5.png" />

<Info>
You can review the CAS settings at any time in `Assets > CleverAdsSolutions > Android / iOS Settings`.
</Info>

## Next steps
CAS Publishing Hub only installs and configures the SDKs. To finish the integration, you still need to add the code to your app:
1. [Integrate the CAS SDK](/unity/initialize-cas) - initialize CAS and add the ad formats you selected. To let an AI assistant do it, give it the instruction file [cas-unity.md](https://github.com/cleveradssolutions/docs/blob/main/llm-guides/cas-unity.md).
2. [Integrate Tenjin](/unity/tenjin-integration) - set up in-app purchase tracking.
```

### Configuring SDK

Source: https://production.docs.page/docs/unity/configuring-sdk

```mdx

In your Unity project, navigate to `Assets > CleverAdsSolutions > Settings` to create and modify default settings for each native platform.  
<Info>
Repeat the following steps for each platform in Android Settings and iOS Settings windows.
</Info>

<Image width="398" alt="image" src="/assets/unity/Configuring-SDK-1.png" />

## Manager Ids
In most cases, a CAS Manager Id is the same as the Android App's package name, and the iOS App's store Id.
- A [package name](https://developer.android.com/studio/build/application-id) uniquely identifies your app on the device and in the Google Play Store.
- The store ID of an iOS app uniquely identifies your app in the Apple App Store.
- You can find an app's store ID in the URL of your app’s Apple App Store listing. For example, the URL of an app page is `apps.apple.com/us/app/id123456789`. The app's store ID is `123456789`.
-  If you haven't created an CAS account and registered an app yet, now's a great time to do so at [CAS.ai](https://cas.ai). 
- In a real app, it is important that you use your actual CAS manager ID.  

## Select ad formats to use
To improve the performance of your application, we recommend that you only allow ad types that will actually be used in the application.  
Your choice helps us configuring mediation in the most effective way for you, depending on the chosen ad formats.  

## Select target audience
Select the audience your game is targeting.  
The changing audience will change the availability of the mediation network dependency.  
- Mixed - The app is intended for audiences of all ages.
- Children - Children restrictions and [Google Play Families Policies](https://support.google.com/googleplay/android-developer/answer/12918983?hl=en) participation apply to the app. Audience under 12 years old.
- NotChildren - Audience over 12 years old only. There are no restrictions on ad filling.  

<Info>
Follow the instructions provided in the settings window.   
Read more about [COPPA compliance](unity/privacy-regulations).
</Info>

## Add Ads Solution
<Warning>
CAS.AI is a mediation SDK with no built-in live ad inventory. At least one ad network adapter or solution must be integrated before publishing to display ads and generate revenue.
</Warning>

Clever Ads Solutions provide ready-made solutions for you to choose from.
- An **Optimal Ads Solutions** contains a number of stable partner networks that are recommended for use in most applications.  
- A **Families Ads Solutions** designed for applications tagged at a children's audience.  
  - For Android, solution is fully compatible with the Google Play Families Policies.
  - For iOS, solution is NOT intended for apps in [Apple Kids Category].

In the following table, you can see all the ad networks supported by Clever Ads Solutions. And a list of partners that are included in the Optimal and Families Ads solutions.  

<Success>  
Changing dependencies will change the Android project setting. Use Android Resolver at bottom of the window after the dependencies changed.
</Success>

<Warning>  
Some ad networks require you to do Additional integration steps: [Meta AudienceNetwork](unity/additional-meta-audiencenetwork-steps)
</Warning>

## Advanced Integration
Advanced integration makes it possible to choose any variations of mediation networks.
Feel free not to use ready-made solutions, and choose which mediated ad networks you want to integrate by checking the boxes in `Mediation Adapters` section of settings window.

<Info>  
Access to the monetization of the `beta` ad sources is closed.  
If you would like to monetize by one of these ad sources, please contact your account manager.
</Info>

## Cross-promotion
Cross-promotion is an app marketing strategy in which app developers promote one of their titles on another one of their titles. Cross promoting is especially effective for developers with large portfolios of games as a means to move users across titles and use the opportunity to scale each of their apps. This is most commonly used by hyper-casual publishers who have relatively low retention, and use cross promotion to keep users within their app portfolio.  

Start your cross promotion campaign with CAS [here](https://cas.ai).
```

### Enabling test ads

Source: https://production.docs.page/docs/unity/enabling-test-ads

```mdx

This guide explains how to enable test ads in your ads integration. It's important to enable test ads during development so that you can click on them without charging CAS advertisers.

<Error>  
We strongly suggest that you enable test ads mode when you validate the integration.  If you click on too many ads without being in test mode, you risk your account being flagged for invalid activity.
</Error>

There are two ways to get test ads:
- [Enable test ad mode](unity/enabling-test-ads#enable-test-ad-mode) for all devices.
- [Set device ids to test ad](unity/enabling-test-ads#enable-test-devices).

Ads with Test Ads mode are safe to click. Requests, impressions, and clicks on test ads will not show up in your account's reports.  
Test full-screen ads displays details of CAS integration and tips for solving errors. Go to the Mediation Adapters section to make sure that the advertising networks you want are integrated correctly.

<Image height="500" alt="image" src="/assets/Enabling-test-ads-1.jpg" />
<Image height="500" alt="image" src="/assets/Enabling-test-ads-2.jpg" />

## Enable test ad mode
The quickest way to enable testing is to use test ad mode. The test ad mode are not associated with your CAS account, so there's no risk of your account generating invalid traffic when using these test ad mode.

1. In your Unity project, navigate to `Assets > CleverAdsSolutions > Settings` to create and modify default settings for each native platform.
2. Check Test ad mode.
3. Use any no empty Manager ID. For example `demo` or your CAS Manager ID.

<Image width="411" alt="image" src="/assets/unity/Enabling-test-ads-3.png" />  

<Info>
Test Ad mode is automatically enabled for builds marked as development in the Unity Build Settings.
</Info>

## Enable test devices
If you want to do more rigorous testing with production-looking ads, you can now configure your device as a test device and use your own manager id. Test devices can either be added programmatically.

Follow the steps below to add your device as a test device.
1. Run an app configured with the CAS on device.
2. Check the console or logcat output for a message that looks like this:
```
To get test ads on this device, set "12345678901234567890123456789012"
```
3. Copy your alphanumeric test device ID to your clipboard.
4. Modify your code to set the test device ID through `SetTestDeviceIds` before CAS manager initialize.
```csharp
CAS.MobileAds.settings.SetTestDeviceIds(new[] {
   "12345678901234567890123456789012"
});
```

<Info>
Be sure to remove the code that sets these test devices before you release your app.
</Info>

5. Re-run your app. 
6. Well done, ads on this device are safe to click. Requests, impressions, and clicks on ads in test mode will not show up in your account's reports.
```

### Firebase Analytics

Source: https://production.docs.page/docs/unity/firebase-integration

```mdx

<Success>
**Set up with an AI assistant (LLM)**

You can set up Firebase Analytics with the help of an AI assistant (Claude, Cursor, GitHub Copilot, etc.). Give it the instruction file [firebase-ga4-setup.md](https://github.com/cleveradssolutions/docs/blob/main/llm-guides/firebase-ga4-setup.md) - attach it to the chat or share its link - and ask the assistant to follow it. The guide walks the assistant through the complete setup. If you prefer to do it yourself, follow the manual steps below.
</Success>

Setting up Firebase lets your project collect analytics and export raw event data, which CAS.AI uses to evaluate performance and prepare a test purchase. Follow the steps below in order.

## Create a Firebase project

<Info>
If you already have a Firebase project, you can skip this step and continue with the existing one.
</Info>

1. Go to the [Firebase console](https://console.firebase.google.com/) and log in with your Google account.
2. Press `Add project` and follow the prompts to name your project.
3. Keep `Enable Google Analytics for this project` turned on, choose or create a Google Analytics account, then press `Create project`.
4. Press `Add app` to register your app, then download its configuration file and add it to your project. Without it, the Firebase SDK won't initialize.

## Share permissions

Access has to be granted in three places: Firebase, Google Analytics and Google Cloud. The tables list the minimum required role for each account - a higher role also works.

### Firebase

- Go to: `Project Settings > Users and permissions` and press `Add member`

| Account | Firebase role |
|---|---|
| `publishing_admin@cas.ai` | Editor |
| `Serhii.Liakh@cas.ai` | Editor |
| `cas_firebase_user@cas.ai` | Editor |

### Google Analytics

- Go to: `Admin > Property > Property Access Management` and press `+`

| Account | Google Analytics role |
|---|---|
| `publishing_admin@cas.ai` | Editor |
| `Serhii.Liakh@cas.ai` | Editor |
| `cas_firebase_user@cas.ai` | Administrator |

<Info>
`cas_firebase_user@cas.ai` runs our automated integration checks - Google Analytics only exposes the access list to Administrators via API, so it needs that specific role to work.
</Info>

### Google Cloud

- Go to: [Google Cloud Console](https://console.cloud.google.com/), `IAM & Admin > IAM`, and press `Grant access`:

| Account | BigQuery role |
|---|---|
| `core-automation@data-warehouse-2025-0424.iam.gserviceaccount.com` | BigQuery Data Editor |
| `viktor-trukhnov@data-warehouse-2025-0424.iam.gserviceaccount.com` | BigQuery Data Viewer |
| `superset-users@data-warehouse-2025-0424.iam.gserviceaccount.com` | BigQuery Data Viewer |

## Switch to the Blaze plan
Exporting data to BigQuery, which you'll set up below, is only available on the paid `Blaze` plan.
- Check the current plan at the bottom of the left panel.
- If the project is on `Spark`, open the billing dialog and upgrade to `Blaze`.
<Info>
`Blaze` is pay-as-you-go but includes a free usage tier — you're only charged if your project exceeds the free limits, so the switch itself costs nothing.
</Info>

## Set up integrations
Go to: `Project settings > Integrations`. Both BigQuery and Google Play are linked from this tab.

<Image width="650" alt="image" src="/assets/unity/publishers/integrations-tab.png" />

### Link BigQuery
1. Go to: `BigQuery > Link`, then continue through the linking flow.
2. In `Select a region`, choose `europe-central2`.
3. In `Export settings`, check:
   - [x] `Streaming`
   - [x] `Include advertising identifiers in export`

<Image width="650" alt="image" src="/assets/unity/publishers/bigquery-export-updated.png" />

<Warning>
The BigQuery region **must** be `europe-central2`. If a different region is used, the timezone has to be corrected manually in analytics afterwards.
</Warning>

### Link Google Play

<Info>
This step is only required for apps published on **Google Play**. The email you are signed in with must be linked to an account in the Google Play Console.
</Info>

- Go to: `Google Play > Link`, then confirm the connection to associate your app with the project.

<Image width="650" alt="image" src="/assets/unity/publishers/google-play-linking.png" />

## Set up the GA timezone
In Google Analytics, set the reporting time zone so the exported data lines up with CAS.AI reporting.
- Go to: `Admin > Property settings > Reporting time zone` and choose a `(GMT+03:00)` option.
- Press `Save`.

<Image width="650" alt="image" src="/assets/unity/publishers/Set-Timezone.png" />
```

### Frequently asked questions

Source: https://production.docs.page/docs/unity/frequently-asked-questions

```mdx


## Android build failed

### java.lang.UnsupportedClassVersionError
```
java.lang.UnsupportedClassVersionError: has been compiled 
by a more recent version of the Java Runtime (class file version 61.0), 
this version of the Java Runtime only recognizes class file versions up to 55.0
```

1. Check Unity [Supported SDK Build tools version](https://docs.unity3d.com/6000.0/Documentation/Manual/android-supported-dependency-versions.html)
2. Remove not supported SDK Build tools versions
3. Remove not supported SDK Command-line tools version

### Execution failed for task ':launcher:dexBuilderRelease'.
```
- Could not resolve all files for configuration ':launcher:detachedConfiguration'.
- Failed to transform jetified-ysonetwork-1.2.9-runtime.jar to match attributes {artifactType=ext-dex-dexBuilderRelease, org.gradle.libraryelements=jar, org.gradle.usage=java-runtime}.
- Execution failed for DexingExternalLibArtifactTransform:

/.../transformed/jetified-ysonetwork-1.2.9-runtime.jar.
- Error while dexing.
```

1. Increase min Android API level to 24
2. Enable `Project Settings > Publishing Settings > Minify > Release/Debug`
```

### Google Plays Families Policy

Source: https://production.docs.page/docs/unity/google-plays-families-policy

```mdx

<Info>
If your application does not participate in Families Ads program, then you can safely skip the page. 
</Info>

Google is focused on providing a great experience for families on Google Play and wants to help make sure that any ads served to children are appropriate and compliant with our policies. Review google ads and monetization policy in the [Developer Policy Center](https://play.google.com/about/families/ads-monetization/).  

If your app's target audience includes children and serves ads using an ad SDK, you must use one of the ad SDKs below. The following ad SDKs have self-certified that their compliance with Play’s [Families Ads Program](https://play.google.com/about/monetization-ads/families-ads-program/) requirements.

> ❕Quote from the [Google Families Ads program page](https://support.google.com/googleplay/android-developer/answer/9283445?hl=en).

### Advertising ID
The [advertising ID](https://support.google.com/googleplay/android-developer/answer/6048248?hl=en) is a unique, user-resettable ID for advertising, provided by Google Play services.  

With Android 12 many mediation partners are starting to include the `com.google.android.gms.permission.AD_ID` permission in the SDK’s library manifest but Families Policy, require that apps not use the Ad ID.  
You must prevent the permission from getting merged into your app by including the following element in your manifest.  
To do this, just select `Removed` for `Advertiser ID permission` option in `Assets > CleverAdsSolutions > Android Settings > Other settings` window.
```

### Impression Level Data

Source: https://production.docs.page/docs/unity/impression-level-data

```mdx


CleverAdsSolutions enables you to access detailed information for each impression through the impressions callback APIs. The information includes, for example, which demand source served the ad, the expected or exact revenue associated with it. In addition, it contains granular details to allow you to analyze and, ultimately, optimize user acquisition strategies. 

## AdMetaData
The `AdMetaData` is an class for getting detailed information about the current ad impression, such as revenue and ad creative details.  

Each ad format has a callback to receive an `AdImpression` about the current impression.  
The code below demonstrates how to handle impression events for Interstitial ad and Banner ad:
```csharp
void OnEnable()
{
    if (manager == null) return;
    manager.GetAdView(AdSize.Banner).OnImpression += HandleAdViewImpression;
    manager.OnInterstitialAdImpression += HandleInterstitialAdImpression;
    manager.OnRewardedAdImpression += HandleRewardedAdImpression;
    manager.OnAppReturnAdImpression += HandleAppReturnAdImpression;
}
void OnDisable()
{
    if (manager == null) return;
    manager.GetAdView(AdSize.Banner).OnImpression -= HandleAdViewImpression;
    manager.OnInterstitialAdImpression -= HandleInterstitialAdImpression;
    manager.OnRewardedAdImpression -= HandleRewardedAdImpression;
    manager.OnAppReturnAdImpression -= HandleAppReturnAdImpression;
}

private void HandleAdViewImpression(IAdView view, AdMetaData impression)
{
    // Get ad details of Banner Ad using impression parameter
}
private void HandleInterstitialAdImpression(AdMetaData impression)
{
    // Get ad details of Interstitial Ad using impression parameter
}
private void HandleRewardedAdImpression(AdMetaData impression)
{
    // Get ad details of Rewarded Ad using impression parameter
}
private void HandleAppReturnAdImpression(AdMetaData impression)
{
    // Get ad details of AppReturn Ad using impression parameter
}
```

### Ad revenue
The revenue generated for the impression (USD). The revenue value is either estimated or exact, according to the `priceAccuracy` property. 
```csharp
double revenue = impression.revenue;
```
You can also check the precision estimate for the `revenue` value, as shown in the following example:
```csharp
PriceAccuracy precision = impression.priceAccuracy;
if (precision == PriceAccuracy.Floor)
{
    // The estimated revenue, can also be a minimum price (floor) for ad impression.
}
else if (precision == PriceAccuracy.Bid)
{
    // The revenue provided as part of the real-time auction.
}
else
{
    // The revenue is '0', when the demand source does not agree to disclose the payout of impression. 
}
```

### Ad creative
You can also retrieve information about the current ad (such as its mediated network and creative ID), and you will be able to report creative issues for that ad to our Ad review team.
```csharp
AdType placementType = impression.type;
string creativeId = impression.creativeIdentifier;
AdNetwork network = impression.network;
string networkUnitId = impression.identifier;
string networkSDKVersion = impression.versionInfo;
```

<Warning>  
`impression.creativeIdentifier` may return null.
</Warning>

A list of all supported networks can be found in `AdNetwork` class. For example:
```csharp
if (networkName == AdNetwork.GoogleAds)
{
    // Impression from Google Ads network.
}
```

### User ad summary 
CAS count the number of ad impressions and the total revenue of all formats at the time of a new impression. 
```csharp
int totalImpressions = impression.impressionDepth;
double totalRevenue = impression.lifetimeRevenue;
```

<Info>
Progress is saved between sessions until the user clears your app's data.
</Info>

## Automatic collect ad revenue
The CAS SDK have features to automatically collect ad revenue to Google Analytics and Tenjin Analytics. Contact your account manager for details of enabling automatic events.
#### Google Analytics
If you haven't already, make sure to complete the following tasks:
1. Set up your project and app as described in [Get Started with Analytics](https://firebase.google.com/docs/analytics/get-started).
2. Make sure that you've linked your Firebase project to a Google Analytics account.
3. Ensure that you've included in your app the CAS SDK 3.5.0+.

To measure ad revenue, CAS SDK log [`ad_impression` events](https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#public-static-final-string-ad_impression) whenever your user sees an advertisement in your app. These events contain details such as the ad platform, source, currency, and value. Optionally, the alternative event name can be `CAS_Impression`.  

#### Tenjin
If you haven't already, make sure to complete the following tasks:
1. Set up your project and app as described in [Get Started with Analytics](https://docs.tenjin.com/docs/unity-sdk#sdk-integration).
2. Make sure that you've [initialize tenjin session](https://docs.tenjin.com/docs/unity-sdk#app-initialization). Or provide `TENJIN_SDK_KEY` with CAS SDK initialization to allow CAS initialize Tenjin SDK automatically. 
   `builder.WithMediationExtras("tenjin_key", <TENJIN_SDK_KEY>)`
3. Ensure that you've included in your app the CAS SDK 3.7.2+.

## Custom collect ad revenue
The following code shows an implementation example for log `AD_IMPRESSION` event to Google Analytics.
```csharp
void CollectImpression(AdMetaData impression)
{   
    Firebase.Analytics.Parameter[] AdParameters = {
        new Firebase.Analytics.Parameter("ad_platform", "CAS"),
        new Firebase.Analytics.Parameter("ad_source", impression.network.ToString()),
        new Firebase.Analytics.Parameter("ad_unit_name", impression.identifier),
        new Firebase.Analytics.Parameter("ad_format", impression.type.ToString()),
        new Firebase.Analytics.Parameter("currency", "USD"), // All CAS revenue is sent in USD 
        new Firebase.Analytics.Parameter("value", impression.revenue)
    };
    Firebase.Analytics.FirebaseAnalytics.LogEvent("ad_impression", AdParameters);
}
```
```

### Include Android

Source: https://production.docs.page/docs/unity/include-android

```mdx

The Clever Ads Solutions Unity plugin is distributed with the [EDM4U](https://github.com/googlesamples/unity-jar-resolver) library. This library is intended for use by any Unity plugin that requires access to Android specific libraries (e.g., AARs) or iOS CocoaPods. It provides Unity plugins the ability to declare dependencies, which are then automatically resolved and copied into your Unity project.  

## Configure Gradle
Using [EDM4U](https://github.com/googlesamples/unity-jar-resolver), you will be able to avoid downloading the Android artifacts into your project. Instead, the artifacts will be added to your gradle file during the compilation. 
To enable this process, follow these steps:  
- Go to: `Player Settings > Publishing Settings > Build`
- [x] `Custom Main Gradle Template` to configure third party dependencies.
- [x] `Custom Base Gradle Template` to update Gradle plugin with fix support Android 11.  
  You can read more about fix Gradle plugin with support Android 11 on the [Android Deleveloper page](https://android-developers.googleblog.com/2020/07/preparing-your-build-for-package-visibility-in-android-11.html).  
- [x] `Custom Gradle Properties Template` to use Jetfier by EDM4U.
- [x] `Custom Main Manifest` to modify application manifest.
- [x] `Custom Gradle Settings Template` to include maven repositories  
  Support Android Gradle Plugin version 7.1.0+

![image](https://user-images.githubusercontent.com/22005013/118801877-2afb5e80-b8aa-11eb-8cbf-1a59499c5d5d.png)

## Configure EDM4U
- Go to: `Assets > External Dependency Manager > Android > Settings`  
- [x] `Patch mainTemplate.gradle`  
  The mainTemplate.gradle file will be patched with dependencies managed by the Android Resolver.
- Save your changes, by pressing `OK`

In the Unity editor, select `Assets > External Dependency Manager > Android Resolver > Resolve`. The Unity External Dependency Manager library will append dependencies to `mainTemplate.gradle` of your Unity app.

## Execute events on Unity Thread
Advertising events for the Android runtime are queued to be called during the next `Update()` cycle. This behavior is safe for using UnityEngine components in advertising events. However, because Unity does not call `Update` while displaying fullscreen ads, all ad events will only be triggered after closing the fullscreen ad and returning to the Unity game.  

If you want to receive callbacks from the ad without waiting for the ad to close, you can disable the `isExecuteEventsOnUnityThread` property in the settings. Enabled by default.

```c#
CAS.MobileAds.settings.isExecuteEventsOnUnityThread = false;
```
You will also need to use `CAS.EventExecutor.Add(Action)` to access Unity Engine components, where Action will be executed during the next `Update()` cycle.

<Info>
isExecuteEventsOnUnityThread property used Android runtime only and enabled by default.
</Info>

## (Optional) Override Gradle versions
CAS have option to override Gradle Wrapper and Android Gradle Plugin versions in CAS Other Settings. The specified versions will be pre-set for the Android Studio project without requiring manual project export. 

Leave the fields empty to use unity original Gradle versions.

#### Gradle Wrapper version
Supported strings with full https url or just version number, for example `7.2` or full url:
```
https\://services.gradle.org/distributions/gradle-7.2-bin.zip
```

#### Android Gradle Plugin version
Supported version strings only, for example `4.2.2`.


<Info>
Please ensure compatibility of all build components when using this option. See official Gradle and Android Gradle Plugin [compatibility table here](https://developer.android.com/build/releases/gradle-plugin#updating-gradle)
</Info>
```

### Include iOS

Source: https://production.docs.page/docs/unity/include-ios

```mdx

The Clever Ads Solutions Unity plugin is distributed with the [EDM4U](https://github.com/googlesamples/unity-jar-resolver) library. This library is intended for use by any Unity plugin that requires access to iOS CocoaPods. It provides Unity plugins the ability to declare dependencies, which are then automatically resolved and copied into your Unity project.  

## Install Cocoapods
iOS dependencies are identified using  [Cocoapods](https://cocoapods.org). CocoaPods resolve is run as a post build process step.  
Make sure that Cocoapods is installed: 
In the Unity editor, select: `Assets > External Dependency Manager > iOS Resolver > Install Cocoapods`  

<Warning>  
Use the generated `.xcworkspace` instead of the standard Xcode project. An xcworkspace is generated that includes the required dependency libraries. 
</Warning>

## Add User Tracking usage description
To use the AppTrackingTransparency framework:
Set up a `NSUserTrackingUsageDescription` to display a system-permission alert request for your app installed on end-user devices.  
In Unity, use `Assets > Clever Ads Solutions > iOS Settings` menu to check:  
- [x] User Tracking Usage description  

And fill table for every language yon want with the [ISO-639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) in the first column and localized description in second column.  
If you want to use the description in English only, remove the rest of the languages.  

## Application pause on background
Indicates if the Unity app should be automatically paused when a full screen ad (Interstitial or Rewarded video ad) is displayed.  
Enabled by default.  
Change the flag at any time using the following method:
```c#
CAS.MobileAds.settings.iOSAppPauseOnBackground = false;
```

## SKAdNetwork
SKAdNetwork is a privacy safe method provided by Apple for ad networks to track installs. Up until iOS 14, most ad network campaign attribution has been based on a user's IDFA, but on iOS 14 and beyond, IDFAs will be less usable as a way to attribute which users have installed based on which ads they have interacted with.

The CAS Unity Plugin **automatically updates** your app’s `Info.plist` with network-specific identifiers.

<Info>
To learn why these identifiers matter and what you lose without them, see [Apple Ad Attribution](general/apple-ad-attribution).
</Info>

## Mute Other Audio Sources
Known issue when the **sounds is disabled in the application** after closing advertising with enabled "Mute Other Audio Sources" option. We will continue to look for ways to solve the conflict.  

Please turn off the option `Mute Other Audio Source` in `Edit > Project Settings > Player > iOS > Other Settings` menu.  
- [ ] Mute Other Audio Source
```

### Initialize CAS SDK

Source: https://production.docs.page/docs/unity/initialize-cas

```mdx


# Initialize MediationManager
To display ads, you must initialize the mediation manager with a unique `managerID`.   
This needs to be done only once for each manager, ideally at app launch.  

If you haven't created an CAS account and registered an app yet, now's a great time to do so at https://cas.ai. In a real app, it is important that you use your actual CAS manager ID.  

The settings for initializing the mediation manager are contained in a [IManagerBuilder](unity/configuring-sdk#allowed-ads-types-in-app) implementation.  
The IManagerBuilder is unique for each supported runtime platform and can be created and modified using the editor `Assets > CleverAdsSolutions > Platform Settings` menu.  
Also you can change any properties of the asset using `CAS.MobileAds.BuildManager()`.  

Here's an example of how to call `Build()` within the `Start()` method of a script attached to a GameObject:

```c#
using CAS;

class CleverAdsSolutionsDemoScript : MonoBehaviour
{
    public void Start()
    {
        IMediationManager manager = GetAdManager();
    }
    
    public static IMediationManager GetAdManager()
    {
        // Configure MobileAds.settings before initialize
        return MobileAds.BuildManager()
           // Optional initialize listener
           .WithCompletionListener((config) => {
                // The CAS SDK initializes if the error is `null`
                string initErrorOrNull = config.error;
                string userCountryISO2OrNull = config.countryCode;
                IMediationManager manager = config.manager;
                
                // True if the user is protected by GDPR or other regulations
                bool protectionApplied = config.isConsentRequired;
                
                // The user completes the consent flow
                ConsentFlow.Status consentFlowStatus = config.consentFlowStatus;
           })
           .Build();
    }
}
```

The `WithCompletionListener` may be called with an error. In this case, the SDK will attempt to reinitialize and the listener will be called again until the error is resolved.

<Error>  
Do not initialize mediated advertising SDKs (CAS does that for you).  
Not following this step will result in noticeable integration issues.
</Error>

<Info>
If you are using Assembly Definition for scripts and see the following  
`error CS0103: The name 'MobileAds' does not exist in the current context`  
then add Assembly Definition Reference to our assembly with name `CleverAdsSolutions`.
</Info>

## Ads processing
CAS have functionality to limit the processing of specific `AdType`.  
This can be useful when you need to improve application performance by turning off unused formats.  
Or if you have determined that the user will no longer need to be shown ads, for example after purchase.   
The default ad type activity is selected in the [settings window](unity/configuring-sdk#allowed-ads-types-in-app).  
However, the state can be changed after initialization using the following methods:
```cs
manager.SetEnableAd(AdType.Interstitial, false);
```
- If processing is inactive then all calls to the selected ad type will fail with error `AdError.ManagerIsDisabled`.  
- ⚠️ Turning off the processing leads to the complete destruction of the ready ads from memory. And reactivation after destruction requires a new load of ads to memory.
- The state will not be saved between sessions.

## Retrieve the Version Number
To programmatically retrieve the Unity Plugin and the native SDK version number at runtime, CAS provides the following strings:
```cs
string pluginVersion = CAS.MobileAds.wrapperVersion;
string nativeSDKVersion = CAS.MobileAds.GetSDKVersion();
```

## (optional) Trial ad-free interval
Set the time interval during which users can enjoy an ad-free experience while retaining access
to Rewarded Ads and App Open Ads formats. This interval is defined from the moment of the initial
app installation, in seconds. Within this interval, users enjoy privileged access to the
application's features without intrusive advertisements.

```csharp
int secondsIn7Days = 604800;
CAS.MobileAds.settings.trialAdFreeInterval = secondsIn7Days;
```
```

### Interstitial Ad object

Source: https://production.docs.page/docs/unity/interstitial-ad-object

```mdx


Interstitial ads are full-screen ads that cover the interface of their host app. They're typically displayed at natural transition points in the flow of an app, such as during the pause between levels in a game. When an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.  

This guide explains how to integrate interstitial ads into a Unity app.    

## Add an InterstitialAdObject to the scene
1. Add an GameObject to your scene using `GameObject > Create Empty` in the Unity Editor.
2. Add Component `CleverAdsSolutions/Interstitial Ad Object` in the inspector to new GameObject.
3. Select [Manager ID](unity/configuring-sdk#manager-ids) from settings asset for each runtime platform.
4. Invoke `Present()` method to show the interstitial ad.  

<Image width="326" alt="image" src="/assets/unity/Interstitial-Ad-object-1.png" />


<Info>
An InterstitialAdObject does not have any rendered components. Therefore, you can place the GameObject anywhere in the scene.
</Info>

## Load Ad callbacks
- **On Ad Loaded**  
The event is invoked when the interstitial ad has finished loading.
- **On Ad Failed To Load**  
The event is invoked when the interstitial ad fails to load. The Message parameter describes the type of failure that occurred.

## Content callbacks
- **On Ad Failed To Show**  
The event is invoked when the interstitial ad failed to show. The Message parameter describes the type of failure that occurred.
- **On Ad Shown**  
The event is invoked when the interstitial ad is shown.
- **On Ad Clicked**  
The event is invoked when the user clicks on the interstitial ad.
- **On Ad Impression**  
The event is invoked when the ad count impression with [Impression Level Data](unity/impression-level-data) and `AdMetaData`.
- **On Ad Closed**  
The event is invoked when the interstitial ad is closed.

## Unity Events sample
You can implement functions that correspond to ad callbacks. For example, if you want to handle when a interstitial ad fails to show:
1. Create a function compatible with the ad callback in custom component.
```c#
public void OnInterstitialAdFailedToShow(string reason) {
    Debug.Log("Interstitial ad failed to show: " + reason);
}
```
2. Attach the script which contains the above function to any GameObject in the scene.
3. Click the **+** button, then drag & drop the GameObject that you've attached the script to.
4. Select the function that you want to link to the ad callback. For the parameterized ad callbacks, select the function to accept the dynamic variable so you can get the parameter value from the SDK.

## Use InterstitialAdObject from script
Get the interstitial ad instance from the script:
```c#
InterstitialAdObject interstitial = adObject.GetComponent<InterstitialAdObject>();
```
Show the interstitial ad:
```c#
interstitial.Present();
```

## Some best practices
- **Consider whether interstitial ads are the right type of ad for your app.**  
Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, such as sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it's easy to present an interstitial ad without disrupting their experience. Make sure you consider at which points in your app's workflow you'll display interstitial ads and how the user is likely to respond.  
- **Remember to pause the action when displaying an interstitial ad.**  
There are a number of different types of interstitial ads: text, image, video, and more. It's important to make sure that when your app displays an interstitial ad, it also suspends its use of some resources to allow the ad to take advantage of them. For example, when you make the call to display an interstitial ad, be sure to pause any audio output being produced by your app. You can resume playing sounds in the `OnInterstitialAdClosed` event handler, which will be invoked when the user has finished interacting with the ad. In addition, consider temporarily halting any intense computation tasks (such as a game loop) while the ad is being displayed. This will make sure the user doesn't experience slow or unresponsive graphics or stuttered video.
- **Don't flood the user with ads.**  
While increasing the frequency of interstitial ads in your app might seem like a great way to increase revenue, it can also degrade the user experience and lower clickthrough rates. Make sure that users aren't so frequently interrupted that they're no longer able to enjoy the use of your app.
```

### Interstitial Ads

Source: https://production.docs.page/docs/unity/interstitial-ads

```mdx


Interstitial ads are full-screen ads that cover the interface of their host app. They're typically displayed at natural transition points in the flow of an app, such as during the pause between levels in a game. When an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.  

This guide explains how to integrate interstitial ads into a Unity app.  

Enable Interstitial Ads for your game in `Assets > CleverAdsSolutions > Settings` menu:  
<Image width="257" alt="image" src="/assets/unity/Interstitial-Ads-1.png" />

> ❕For easier ads integration using the Unity Editor, try the new [InterstitialAdObject](unity/interstitial-ad-object).

## Ad events
To further customize the behavior of your ad, you can hook into a number of events in the ad's lifecycle: loading, opening, closing, and so on. Listen for these events by registering a delegate for the appropriate event, as shown below.

```csharp
manager.OnInterstitialAdLoaded += AdLoaded;
manager.OnInterstitialAdFailedToLoad += AdFailedToLoad;
manager.OnInterstitialAdShown += AdShown;
manager.OnInterstitialAdFailedToShow += AdFailedToShow;
manager.OnInterstitialAdClicked += AdClicked;
manager.OnInterstitialAdClosed += AdClosed;

void AdLoaded()
{
    Debug.Log("Interstitial ad loaded");
}
void AdFailedToLoad(AdError error)
{
    Debug.Log("Interstitial failed to load an ad with error: " + error.GetMessage());
}
void AdShown()
{
    Debug.Log("Interstitial ad full screen content opened");
}
void AdFailedToShow(string error)
{
    Debug.LogError("Interstitial ad failed to open full screen content: " + error);
}
void AdClicked()
{
    Debug.Log("Interstitial ad was clicked");
}
void AdClosed()
{
    Debug.Log("Interstitial ad full screen content closed");
}
```

<Info>
When an error occurs during ad impression, executed the `OnInterstitialAdFailedToShow` only.  In this case the `OnInterstitialAdClosed` will not be executed, since the impression is not considered successful.
</Info>

Read more about event `OnInterstitialAdImpression` with [Impression Level Data](unity/impression-level-data) and `AdMetaData`.  
## Load an Ad
By default, the **auto-load ads mode is used** and a load method does not need to be called.  
Call manual load ad before each show if you use `LoadingManagerMode.Manual` only.  

Use `AdType.Interstitial` parameter for load ad:
```c#
manager.LoadAd(AdType.Interstitial);
```

## Check the ad availability
You can ask for the ad availability directly by calling the following function:
```c#
bool adLoaded = manager.IsReadyAd(AdType.Interstitial);
```
Avoid using `IsReadyAd` every frame in `Update` or `Coroutine`; instead, subscribe to the `OnInterstitialAdLoaded` event. This method call the native SDK and can affect the performance of your game. 

You don't have to check `IsReadyAd` before showing an ad; instead, subscribe to the `OnInterstitialAdFailedToShow` event, which will be triggered if the ad isn't ready to show.

## Show the Ad
Use `AdType.Interstitial` parameter to show ad:
```c#
manager.ShowAd(AdType.Interstitial);
```

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.
```cs
manager.ShowAd(AdType.Interstitial, "BestPlace");
```

## Minimum interval between impressions
You can limit the posting of an interstitial ad to a period of time in seconds after the ad is closed, during which display attempts will fail.
That the interval starts only after the Interstitial Ad **closes** `OnInterstitialAdClosed`.  
During interval after ad closed, display attempts will fire event `OnInterstitialAdFailedToShow` with `AdError.IntervalNotYetPassed`.  

Change the interstitial ad impression interval using the following method:
```cs
CAS.MobileAds.settings.interstitialInterval = interval;
```

If you need to wait for a period of time after the start of the game or after showing a Rewarded Ad until next Interstitial Ad impression then please call the following method:
```cs
CAS.MobileAds.settings.RestartInterstitialInterval();
```

<Info>
We recommend define the interstitial ad impression interval once before mediation manager is initialized to be able to override the value remotely via the web interface.
</Info>

## Muted Ads Sounds
Sounds in Interstitial and Rewarded ads mute state. Disabled by default.  
```cs
CAS.MobileAds.settings.isMutedAdSounds = mute;
```

## Some best practices
- **Consider whether interstitial ads are the right type of ad for your app.**  
Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, such as sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it's easy to present an interstitial ad without disrupting their experience. Make sure you consider at which points in your app's workflow you'll display interstitial ads and how the user is likely to respond.  
- **Remember to pause the action when displaying an interstitial ad.**  
There are a number of different types of interstitial ads: text, image, video, and more. It's important to make sure that when your app displays an interstitial ad, it also suspends its use of some resources to allow the ad to take advantage of them. For example, when you make the call to display an interstitial ad, be sure to pause any audio output being produced by your app. You can resume playing sounds in the `OnInterstitialAdClosed` event handler, which will be invoked when the user has finished interacting with the ad. In addition, consider temporarily halting any intense computation tasks (such as a game loop) while the ad is being displayed. This will make sure the user doesn't experience slow or unresponsive graphics or stuttered video.
- **Don't flood the user with ads.**  
While increasing the frequency of interstitial ads in your app might seem like a great way to increase revenue, it can also degrade the user experience and lower clickthrough rates. Make sure that users aren't so frequently interrupted that they're no longer able to enjoy the use of your app.

<Success>  
[HelloWorld example](https://github.com/cleveradssolutions/CAS-Unity-Sample/blob/master/Assets/SampleCSharp/CSharpSampleController.cs) — a minimal implementation of all ad formats 
</Success>
```

### Manager Ad object

Source: https://production.docs.page/docs/unity/manager-ad-object

```mdx

To display ads, you must initialize the mediation manager with a unique Manager ID.   
This needs to be done only once for each manager, ideally on first scene.  

1. Add an GameObject to your scene using `GameObject > Create Empty` in the Unity Editor.
2. Add Component `CleverAdsSolutions/Initialize Manager Ad Object` in the inspector to new GameObject.
3. Select [Manager ID](unity/configuring-sdk#manager-ids) from settings asset for each runtime platform.  
4. Invoke a `Initialize()` method to begin initialization.

<Image width="421" alt="image" src="/assets/unity/Manager-Ad-object-1.png" />

- **Initialize On Awake**  
Automatically invoke the `Initialize()` method when the component is awake.
 - **Consent Flow Enabled**  
 Use Consent Flow in ads initialization.
  - **Consent Flow**  
   If desired, select an ConsentFlow Ad Object for additional options or leave it blank.
- **Meta Audience Network Privacy**  
Read more about [Additional Meta AudienceNetwork steps](unity/additional-meta-audiencenetwork-steps).
- **OnInitialized**  
The Unity event will be invoked when the Mediation Manager is initialized and ready.
- **OnInitializationFailed**  
The Unity event will be invoked when the Mediation Manager initialization failed.  
Wait for the OnInitialized event to call the manager.
```

### Other Options

Source: https://production.docs.page/docs/unity/other-options

```mdx


## Verbose Debug logging
The enabled Debug Mode will display a lot of useful information for debugging about the states of the SDK with tag `CAS.AI`.  
Disabled by default. Disabling Debug Mode may improve application performance.  
You can enable logging in `Assets > CleverAdsSolutions > Settings` menu or change the flag at any time using the following method:
```cs
CAS.MobileAds.settings.isDebugMode = enabled;
```

<Info>
If you have discovered the problem in the work of the SDK, please provide us with a description of the problem along with the full log of your device.
</Info>

## Loading mode
Managing ad availability is not easy. Keeping a balance between maximum ad availability while minimizing waste (network calls - which may affect user experience and data usage - and calls to mediated networks APIs - which may negatively impact eCPM if their inventory never gets to be shown to a user) can turn out to be harder than expected. In fact, often, it is simply guess work as you cannot predict ahead of time when a user will reach a moment in your application or game where it makes sense to show an Interstitial or offer the possibility to watch a Rewarded ad.

When you try to time your ad requests, this often results in not having a fill when you need it or having wasted fills that are never shown.  

<Info>
The CAS SDK provides an “auto-request” feature to address this problem.   
By default, CAS SDK starts with auto-request enabled for all managers.  
</Info>

This means two things:
- When a user finishes watching an ad, CAS immediately tries to replace that ad.
- When a certain placement has trouble obtaining a fill (no traditional mediated network has available inventory and no programmatic demand is bidding within a predetermined amount of time), CAS continues trying to ensure that placement gets a fill by restarting the entire ad request process. This is performed in exponentially increasing time intervals to optimize the chances of getting a fill while minimizing usage of device resources.  

However, you can choose to disable auto-request when you set `Manual` loading mode.

|        Mode        |  Load<sup>[*1](unity/other-options#load-f-1)</sup>  | Impact on App performance | Memory usage |        Actual ads<sup>[*2](unity/other-options#actual-f-2)</sup>       |
|:------------------:|:------:|:-------------------------:|:------------:|:------------------------:|
|   FastestRequests  |  Auto  |         Very high         |     High     |       Most relevant      |
|    FastRequests    |  Auto  |            High           |    Balance   |      High relevance      |
|  Optimal *(Default)*  |  Auto  |          Balance          |    Balance   |          Balance         |
|   HighPerformance  |  Auto  |            Low            |      Low     |       Possible loss      |
| HighestPerformance |  Auto  |          Very low         |      Low     |       Possible loss      |
|       Manual      | Manual<sup>[*3](unity/other-options#manual-f-3)</sup> |          Very low         |      Low     | Depends on the frequency |

Change the Waterfall loading mode using the following method:
```c#
CAS.MobileAds.settings.loadingMode = mode;
```
<Info>
You can set this option using the `Assets > CleverAdsSolutions > Settings > Other Settings`  window.
</Info>

## Auto check for CAS updates
CAS check for new versions of the unity plugin when opening the settings window. If a new version is found then you will be prompted to update the plugin.  
You can disable the auto check update and use the `Check for Updated` button at the top of the settings window.
<Info>
You can set this option using the `Assets > CleverAdsSolutions > Settings > Other Settings`  window.
</Info>
```

### Privacy Regulations

Source: https://production.docs.page/docs/unity/privacy-regulations

```mdx


CleverAdsSolutions requires you to set flags indicating whether users are in an age-restricted category.

## Prohibition on Personal Information from Children
Publishers may designate all inventory within their applications as being child-directed or as COPPA-applicable though our UI. Publishers who have knowledge of specific individuals as being COPPA-applicable should make use of the API discussed below to inform CAS and all downstream consumers of this information.  

<Info>
Read more about [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy)
</Info>

### Audience.Children
If you know that the user falls within an age-restricted category (i.e., under the age of 16), you must set the `Children` audience flag:
```csharp
CAS.MobileAds.settings.taggedAudience = Audience.Children;
```
It also allows application to comply with the Google Play Families Policy requirements:
 - Ads displayed to those users do not involve interest-based advertising or remarketing;
 - Ads displayed to those users present content that is appropriate for children;
 - Ads displayed to those users follow the Families ad format requirements;
 - Compliance with all applicable legal regulations and industry standards relating to advertising to children.
 
### Audience.NotChildren
If you know that the user does not fall within an age-restricted category, you must set the `NotChildren` audience flag:
```csharp
CAS.MobileAds.settings.taggedAudience = Audience.NotChildren;
```

### Audience.Mixed
The user's age has not been determined.
```c#
CAS.MobileAds.settings.taggedAudience = Audience.Mixed;
```
If your app's target age groups include both children and older audiences, any ads that may be shown to children must comply with Google Play's Families Ads Program.  
A neutral age screen must be implemented so that any ads not suitable for children are only shown to older audiences.  
A neutral age screen is a mechanism to verify a user's age in a way that doesn't encourage them to falsify their age and gain access to areas of your app that aren't designed for children, for example, an age gate.
```

### Prerequisites for App Transfer to CAS.AI Publishing

Source: https://production.docs.page/docs/unity/publisher-integrations

```mdx
 
<Success>
You don't need to complete any additional integrations if your app is not part of the CAS.AI Mobile Game Publisher program.
</Success>

This guide helps publishers prepare a project for working with CAS.AI Mobile Game Publisher. By the end you will have analytics and event data flowing out of your app, and the attribution setup needed to run a test purchase.
 
The preparation consists of three parts. Complete them together with your CAS.AI manager, who will provide the keys and credentials referenced in the steps.

## 1. Set up the Firebase project
Create and link a Firebase project to collect analytics and export event data.

<Card title="Firebase" href="/unity/firebase-integration">
Create the project, share permissions and link BigQuery.
</Card>

## 2. Integrate the CAS SDK
Install the CAS SDK in the [standard way](/unity), or use [CAS Publishing Hub](/unity/cas-publishing-hub-integration), which installs and configures the CAS SDK, Tenjin and Firebase Analytics in one wizard.

## 3. Integrate Tenjin
Set up Tenjin to attribute installs and track in-app purchases.

<Card title="Tenjin" href="/unity/tenjin-integration">
Report in-app purchases to Tenjin.
</Card>
```

### Purchase Info

Source: https://production.docs.page/docs/unity/purchase-info

```mdx

The `PurchaseInfo` class is used to report in-app purchases to CAS.AI. Along with the SDK's ad revenue tracking, this allows you to get a complete picture of a user's total value by combining ad revenue and IAP revenue in one place.

The total reported revenue is calculated as:

```
revenue = quantity * price * currency_rate
```

## Reporting a purchase

Call `CAS.MobileAds.ReportPurchase(...)` with a `PurchaseInfo` object as soon as you've confirmed a completed transaction. This feeds IAP revenue into CAS.AI alongside your ad revenue.

When using Unity IAP, this is typically done when the order is confirmed, for example in the `OnPurchasePending` handler right before you call `ConfirmPurchase(order)`.

### 1. Create `PurchaseInfo`

Build the object from the purchased product's ID, price, currency, and quantity.

```csharp
var purchase = new CAS.PurchaseInfo(
    product.definition.id,
    product.metadata.localizedPrice,
    product.metadata.isoCurrencyCode,
    quantity // optional, 1 by default
);
```

| Parameter | Description |
| --- | --- |
| `productId` | Product identifier from the IAP provider: `product.definition.id` |
| `price` | Price of one purchased item in the selected currency: `product.metadata.localizedPrice` |
| `currency` | ISO 4217 currency code, for example `USD` or `EUR`: `product.metadata.isoCurrencyCode` |
| `quantity` | Number of items being purchased. Defaults to `1` |

### 2. Recommended: attach validation data

Add the store-specific receipt data so CAS.AI can verify the purchase server-side. Use the method that matches the store which processed the purchase.

```csharp
var unityReceipt = JsonUtility.FromJson<UnifiedReceipt>(order.Info.Receipt);
var store = unityReceipt.Store;
var payload = unityReceipt.Payload;
var isSubscriptionType = product.definition.type == ProductType.Subscription;

if (store.Equals("GooglePlay"))
{
    purchase.SetGoogleValidation(payload, isSubscriptionType);
}
else if (store.Equals("AppleAppStore"))
{
    purchase.SetAppleValidation(
        order.Info.transactionID,
        order.Info.Apple?.jwsRepresentation,
        order.Info.Apple?.AppReceipt,
        isSubscriptionType
    );
}
else if (store.Equals("AmazonAppStore"))
{
    purchase.SetAmazonValidation(payload);
}
```

| Method | Store | Parameters |
| --- | --- | --- |
| `SetGoogleValidation` | Google Play | `payload`: JSON string of the Google payload.<br/>`isSubscriptionType`: whether the product is a subscription. |
| `SetAppleValidation` | Apple App Store | `transactionID`: StoreKit transaction identifier.<br/>`jwsRepresentation`: StoreKit 2 signed transaction, can be `null`.<br/>`receiptData`: StoreKit 1 app receipt, can be `null`.<br/>`isSubscriptionType`: whether the product is a subscription. |
| `SetAmazonValidation` | Amazon Appstore | `payload`: JSON string of the Amazon IAP receipt. |
| `SetXsollaValidation` | Xsolla | `orderId`: Xsolla order ID.<br/>`userId`: Xsolla user ID, can be `null`. |

<Info>
Validation data is optional, but it is recommended when available.
</Info>

<Note>
For Amazon Appstore and Xsolla purchases, you are responsible for supplying the price, currency, and quantity values (e.g. from your own product catalog) to ensure revenue is reported accurately.
</Note>

### 3. Report

With the product info and validation data attached, `purchase` is ready to send:

```csharp
CAS.MobileAds.ReportPurchase(purchase);
```

## Automatic forwarding to Tenjin

Purchases reported through `CAS.MobileAds.ReportPurchase(...)` can also be forwarded automatically to Tenjin Analytics, so you don't need a separate integration to get IAP revenue into Tenjin.
```

### Return To Play Ad Object

Source: https://production.docs.page/docs/unity/return-to-play-ad-object

```mdx


This guide explains how to integrate interstitial ads into a Unity app.    

<Warning>  
- The Ad on Return to App is a regular Interstitial Ad. 
- Automatic display is only possible when using autoload Interstitial Ad. 
- The Ad will be displayed only if the Interstitial Ad is currently loaded. After displaying the Interstitial Ad, it will be necessary to load a new advertisement.
- The Ad will not be shown if the interval since the last closure of the Interstitial Ad has not elapsed.
- Do not activate this ad format if your application displays an AppOpen Ad when returning to the app.
</Warning>

## Add a ReturnToPlayAdObject to the scene
1. Add a GameObject to your scene using `GameObject > Create Empty` in the Unity Editor.
2. Add Component `CleverAdsSolutions/Return To Play Ad Object` in the inspector to new GameObject.
3. Select [Manager ID](unity/configuring-sdk#manager-ids) from the settings asset for each runtime platform.
4. Check flag `allowReturnToPlayAd`

<Image width="327" alt="image" src="/assets/unity/Return-To-Play-Ad-Object-1.png" />

<Info>
An ReturnToPlayAdObject does not have any rendered components. Therefore, you can place the GameObject anywhere in the scene.
</Info>

## Load Ad callbacks
- **On Ad Loaded**  
The event is invoked when the ad has finished loading.
- **On Ad Failed To Load**  
The event is invoked when the ad fails to load. The Message parameter describes the type of failure that occurred.

## Content callbacks
- **On Ad Failed To Show**  
The event is invoked when the ad failed to show. The Message parameter describes the type of failure that occurred.
- **On Ad Shown**  
The event is invoked when the ad is shown.
- **On Ad Clicked**  
The event is invoked when the user clicks on the ad.
- **On Ad Impression**  
The event is invoked when the ad count impression with [Impression Level Data](unity/impression-level-data) and `AdMetaData`.
- **On Ad Closed**  
The event is invoked when the ad is closed.

## Unity Events sample
You can implement functions that correspond to ad callbacks. For example, if you want to handle when the ad fails to shown:
1. Create a function compatible with the ad callback in custom component.
```c#
public void OnReturnToPlayAdFailedToShow(string reason) {
    Debug.Log("ReturnToPlay ad failed to show: " + reason);
}
```
2. Attach the script which contains the above function to any GameObject in the scene.
3. Click the **+** button, then drag & drop the GameObject that you've attached the script to.
4. Select the function that you want to link to the ad callback. For the parameterized ad callbacks, select the function to accept the dynamic variable so you can get the parameter value from the SDK.

## Use ReturnToPlayAdObject from script
Get the ReturnToPlay ad instance from the script:
```c#
ReturnToPlayAdObject adObject = adObject.GetComponent<ReturnToPlayAdObject>();
```
Enable ReturnToPlay ad:
```c#
adObject.allowReturnToPlayAd = true;
```
Disable ReturnToPlay ad:
```c#
adObject.allowReturnToPlayAd = false;
```
```

### Rewarded Ad object

Source: https://production.docs.page/docs/unity/rewarded-ad-object

```mdx

Rewarded ads are ads that users have the option of interacting with in exchange for in-app rewards. 

This guide shows you how to integrate rewarded ads into a Unity app. 

## Add an RewardedAdObject to the scene
1. Add an GameObject to your scene using `GameObject > Create Empty` in the Unity Editor.
2. Add Component `CleverAdsSolutions/Rewarded Ad Object` in the inspector to new GameObject.
3. Select [Manager ID](unity/configuring-sdk#manager-ids) from settings asset for each runtime platform.
4. Attach function to `OnReward` event to handle reward.
5. Invoke `Present()` method to show the rewarded video ad.  

<Image width="326" alt="image" src="/assets/unity/Rewarded-Ad-object-1.png" />

- **Restart Interstitial Ad interval on rewarded ad closed**  
The interstitial ad interval will restart after the rewarded ad is closed.
- **OnReward**  
The most important event is called when the user is rewarded for watching a video

<Info>
An RewardedAdObject does not have any rendered components. Therefore, you can place the GameObject anywhere in the scene.
</Info>

## Load Ad callbacks
- **On Ad Loaded**  
The event is invoked when the rewarded ad has finished loading.
- **On Ad Failed To Load**  
The event is invoked when the rewarded ad fails to load. The Message parameter describes the type of failure that occurred.

## Content callbacks
- **On Ad Failed To Show**  
The event is invoked when the rewarded ad failed to show. The Message parameter describes the type of failure that occurred.
- **On Ad Shown**  
The event is invoked when the rewarded ad is shown.
- **On Ad Clicked**  
The event is invoked when the user clicks on the rewarded ad.
- **On Ad Impression**  
The event is invoked when the ad count impression with [Impression Level Data](unity/impression-level-data) and `AdMetaData`.
- **On Ad Closed**  
The event is invoked when the rewarded ad is closed.

## Unity Events sample
You can implement functions that correspond to ad callbacks. For example, if you want to handle when a banner ad fails to load:
1. Create a function compatible with the ad callback in custom component.
```c#
public void OnReward() {
    Debug.Log("The user earned the reward.");
}
```
2. Attach the script which contains the above function to any GameObject in the scene.
3. Click the **+** button, then drag & drop the GameObject that you've attached the script to.
4. Select the function that you want to link to the ad callback. For the parameterized ad callbacks, select the function to accept the dynamic variable so you can get the parameter value from the SDK.

## Use RewardedAdObject from script
Get the rewarded ad instance from the script:
```c#
RewardedAdObject rewarded = rewardedObject.GetComponent<RewardedAdObject>();
```

Before displaying a rewarded ad to users, you must present the user with an explicit choice to view rewarded ad content in exchange for a reward. Rewarded ads must always be an opt-in experience.  

Show the rewarded ad:
```c#
rewarded.Present();
```
```

### Rewarded Ads

Source: https://production.docs.page/docs/unity/rewarded-ads

```mdx


Rewarded ads are ads that users have the option of interacting with in exchange for in-app rewards. 

This guide shows you how to integrate rewarded ads into a Unity app.  

Enable Rewarded Ads for your game in `Assets > CleverAdsSolutions > Settings` menu:  
<Image width="250" alt="image" src="/assets/unity/Rewarded-Ads-1.png"/>

> ❕For easier ads integration using the Unity Editor, try the new [RewardedAdObject](unity/rewarded-ad-object).

## Ad events
To further customize the behavior of your ad, you can hook into a number of events in the ad's lifecycle: loading, opening, closing, and so on. Listen for these events by registering a delegate for the appropriate event, as shown below.


```csharp
manager.OnRewardedAdCompleted += AdCompleted;
manager.OnRewardedAdLoaded += AdLoaded;
manager.OnRewardedAdFailedToLoad += AdFailedToLoad;
manager.OnRewardedAdShown += AdShown;
manager.OnRewardedAdFailedToShow += AdFailedToShow;
manager.OnRewardedAdClicked += AdClicked;
manager.OnRewardedAdClosed += AdClosed;

void AdCompleted()
{
    Debug.Log("The user earned the reward.")
}
void AdLoaded()
{
    Debug.Log("Rewarded ad loaded");
}
void AdFailedToLoad(AdError error)
{
    Debug.Log("Rewarded failed to load an ad with error: " + error.GetMessage());
}
void AdShown()
{
    Debug.Log("Rewarded ad full screen content opened");
}
void AdFailedToShow(string error)
{
    Debug.LogError("Rewarded ad failed to open full screen content: " + error);
}
void AdClicked()
{
    Debug.Log("Rewarded ad was clicked");
}
void AdClosed()
{
    Debug.Log("Rewarded ad full screen content closed");
}
```

<Info>
When an error occurs during ad impression, executed the `OnRewardedAdFailedToShow` only.  In this case the `OnRewardedAdClosed` will not be executed, since the impression is not considered successful.
</Info>

Read more about event `OnRewardedAdImpression` with [Impression Level Data](unity/impression-level-data) and `AdMetaData`.  
## Load an Ad
By default, the **auto-load ads mode is used** and a load method does not need to be called.  
Call manual load ad before each show if you use `LoadingManagerMode.Manual` only.  

Use `AdType.Rewarded` parameter for load ad:
```csharp
manager.LoadAd(AdType.Rewarded);
```

## Check the ad availability
You can ask for the ad availability directly by calling the following function:
```cs
bool adLoaded = manager.IsReadyAd(AdType.Rewarded);
```

Avoid using `IsReadyAd` every frame in `Update` or `Coroutine`; instead, subscribe to the `OnRewardedAdLoaded` event. This method call the native SDK and can affect the performance of your game. 

You don't have to check `IsReadyAd` before showing an ad; instead, subscribe to the `OnRewardedAdFailedToShow` event, which will be triggered if the ad isn't ready to show.

## Show the Ad
Before displaying a rewarded ad to users, you must present the user with an explicit choice to view rewarded ad content in exchange for a reward. Rewarded ads must always be an opt-in experience.  

Subscribe to `OnRewardedAdCompleted` event to reward the user.

Use `AdType.Rewarded` parameter to show ad:
```cs
manager.ShowAd(AdType.Rewarded);
```

### Optional Placement name
An optional placement name for the ad instance that helps categorize and track statistics across different ad placements. Maximum 100 characters allowed for the placement name.
```cs
manager.ShowAd(AdType.Rewarded, "BestPlace");
```

## Muted Ads Sounds
Sounds in Interstitial and Rewarded ads mute state. Disabled by default.  
```cs
CAS.MobileAds.settings.isMutedAdSounds = mute;
```

## Allow Interstitial ads
Sometimes a situation occurs when filling Rewarded ads is not enough, in this case, you can allow the display of Interstitial ads to receiving a reward in any case.  
This option will compare ad cost and serve regular interstitial ads when rewarded video ads are expected to generate less revenue.  
Interstitial Ads does not require to watch the video to the end, but the `OnRewardedAdCompleted` event will be invoked in any case.  
Enabled by default.

Change the flag at any time using the following method:
```c#
CAS.MobileAds.settings.allowInterstitialAdsWhenVideoCostAreLower = allow;
```

<Success>  
[HelloWorld example](https://github.com/cleveradssolutions/CAS-Unity-Sample/blob/master/Assets/SampleCSharp/CSharpSampleController.cs) — a minimal implementation of all ad formats 
</Success>
```

### Targeting options

Source: https://production.docs.page/docs/unity/targeting-options

```mdx

You can now easily tailor the way you serve your ads to fit a specific audience!  
You’ll need to inform our servers of the users’ details so the SDK will know to serve ads according
to the segment the user belongs to.

### User ID
The userID is a unique identifier supplied by your application and must be static for each user across sessions. 
```csharp
CAS.MobileAds.targetingOptions.userID = "user-hash-code";
```

<Warning>  
Your userID should not contain any personally identifiable information such as  an email address, screen name, Android ID (AID), or Google Advertising ID (GAID).
</Warning>

## User Age

Set user age. Limitation: 1-99 and 0 is 'unknown'.

```csharp
CAS.MobileAds.targetingOptions.age = 12;
```

## User Gender

Set user gender.

```csharp
CAS.MobileAds.targetingOptions.gender = Gender.Male;
```

## App Keywords

Set a list of keywords, interests, or intents related to your application. Words or phrases describe
the current activity of the user for targeting purposes.

```csharp
CAS.MobileAds.targetingOptions.SetKeywords(new[] { "words" });
```

## App Content URL

Set the content URL for a website whose content matches the app's primary content. This website
content is used for targeting and brand safety purposes. Limitation: max URL length 512.

```csharp
CAS.MobileAds.targetingOptions.contentUrl = contentUrl;
```

## Track Location Enabled
Collect from the device the latitude and longitude coordinated truncated to the hundredths decimal place. Collect only if your application already has the relevant end-user permissions. Does not collect if the target audience is children.

By default selected in `Assets > CleverAdsSolutions > iOS Settings > Other Settings` menu:
- [x] Location targeting if allowed

Change the flag at any time using the following method:
```csharp
CAS.MobileAds.targetingOptions.locationCollectionEnabled = true;
```
```

### Tenjin

Source: https://production.docs.page/docs/unity/tenjin-integration

```mdx
 
Tenjin handles install attribution and purchase tracking. The CAS SDK initializes Tenjin automatically, so the only thing left to set up is tracking in-app purchases.
 
## Track purchases
Choose one of the following methods to report in-app purchases to Tenjin.

<Accordion title="(Option 1) Report purchases with the CAS SDK">
Report each completed purchase with `CAS.MobileAds.ReportPurchase(...)`. The CAS SDK forwards it to Tenjin automatically, so no separate Tenjin code is needed.

```csharp
// 1. Create PurchaseInfo
var purchase = new CAS.PurchaseInfo(
    product.definition.id,
    product.metadata.localizedPrice,
    product.metadata.isoCurrencyCode,
    quantity // optional, 1 by default
);

// 2. Recommended: attach validation data
var unityReceipt = JsonUtility.FromJson<UnifiedReceipt>(order.Info.Receipt);
var store = unityReceipt.Store;
var payload = unityReceipt.Payload;
var isSubscriptionType = product.definition.type == ProductType.Subscription;

if (store.Equals("GooglePlay"))
{
    purchase.SetGoogleValidation(payload, isSubscriptionType);
}
else if (store.Equals("AppleAppStore"))
{
    purchase.SetAppleValidation(
        order.Info.transactionID,
        order.Info.Apple?.jwsRepresentation,
        order.Info.Apple?.AppReceipt,
        isSubscriptionType
    );
}
else if (store.Equals("AmazonAppStore"))
{
    purchase.SetAmazonValidation(payload);
}

// 3. Report
CAS.MobileAds.ReportPurchase(purchase);
```

See the [Purchase Info](/unity/purchase-info) guide for details on each parameter and validation method.
</Accordion>

<Accordion title="(Option 2) Report purchases with CAS Publishing Hub">
If you installed the SDK with [CAS Publishing Hub](/unity/cas-publishing-hub-integration) and your project uses Unity IAP, report each completed purchase with:

```csharp
CASHub.ReportPurchase(product, order);
```

<Info>
`CASHub.ReportPurchase` is available only when Unity IAP is present in the project.
</Info>
</Accordion>

## Share purchase validation keys
If your app includes in-app purchases, you must provide your manager with the following so Tenjin can track them:
 
- **Public Key** for the Android app — in the Google Play Console, select your app and go to `Monetize > Monetization setup > Google Play Billing > Licensing`. Copy the **Base64-encoded RSA public key**.
- **Shared Secret** for the iOS app (only for subscriptions) — in App Store Connect, select your app and go to `App Information > App-Specific Shared Secret`. Copy the **App-Specific Shared Secret**.

<Warning>
Without the Public Key (Android) and Shared Secret (iOS), Tenjin will not be able to track your purchases.
</Warning>
```

### User Consent Flow

Source: https://production.docs.page/docs/unity/user-consent-flow

```mdx

In order for CAS and our ad providers to deliver ads that are more relevant to your users, as a mobile app publisher, you need to collect explicit user consent.

<Info>
If you implement a CMP that is compliant with IAB TCF v2 ([Transparency & Consent Framework](https://iabeurope.eu/tcf-2-0/)) for your user consent flow, the CAS SDK supports sending the TCF v2 consent to networks. In this case, the CAS Consent Flow will not be shown to the user.
</Info>

<Warning>  
If you integrate your own CMP flow, make sure the flow completes before you initialize the CAS SDK.
</Warning>

### 1. Opt-in consent for the collection and use of personal data in the regions covered by GDPR, CCPA, LGPD, PIPEDA.
Any businesses established are required to comply with GDPR in Europe, CCPA in California, LGPD in Brazil, PIPEDA in Canada or risk facing heavy fines.

<Info>
Keep in mind that it’s best to contact qualified legal professionals, if you haven’t done so already, to get more information and be well-prepared for compliance.   
Read more about:
- GDPR - [General Data Protection Regulation](https://gdpr-info.eu)
- CCPA - [The California Consumer Privacy Act](https://theccpa.org)
- LGPD - [General Personal Data Protection Act](https://lgpd-brazil.info)
- PIPEDA - [The Personal Information Protection and Electronic Documents Act](https://www.priv.gc.ca/en/privacy-topics/privacy-laws-in-canada/the-personal-information-protection-and-electronic-documents-act-pipeda/)
</Info>

### 2. Asking Apple's user permission to track them or access their device’s advertising identifier
With iOS 14.5 and later, you need to receive the user’s permission through the `AppTrackingTransparency` framework in order to track them or access their device’s advertising identifier. Read more about Asking Permission to Track and AppTrackingTransparency Framework on [Apple developer page](https://developer.apple.com/app-store/user-privacy-and-data-use/)

<Warning>  
If an iOS App does not present this request, the IDFA will automatically be zeroed out, which may lead to a significant loss in ad revenue.
</Warning>

## Overview flow
<Image height="400" alt="image" src="/assets/User-Consent-Flow-1.png" />

#### Users will not see the Consent dialog if at least one of following is true
- Users located in regions that are not covered by information protection
- Users who are subject to COPPA restrictions.
#### Users will not see the ATT request if at least one of the following is true
- Users using iOS versions below 14.5
- Users who have indicated that they do not allow apps to ask to track them, by setting *Settings > Privacy, Allow Apps to Request to Track*
- Users with child accounts, or who are under age 18, who are signed in via their Apple ID
- Users who have already answered so far
- The app does not have a usage tracking description in **Info.plist** under `NSUserTrackingUsageDescription` key

## Automatic consent flow
To get consent for collecting personal data of your users, we suggest you use a built-in Consent Flow, comes with a pre-made consent form that you can easily present to your users. That means you no longer need to create your own consent window.  

First, create a utility static property wherever convenient in your application to check if a Consent Flow is obtained for the user.
```c#
public static bool isConsentObtained = true;
```

The user will see the consent flow when your app create CAS Manager. When the user completes the flow, the SDK calls your initialization-completion handler.
```c#
var builder = CAS.MobileAds.BuildManager();
builder.WithConsentFlow(
    new ConsentFlow()
        .WithCompletionListener((status) => 
        {
            isConsentObtained = status == ConsentFlow.Status.Obtained;
        })
);
builder.WithCompletionListener((config) => 
{
    // The user completes the flow here
    
    // Initialize other 3rd-party SDKs
});
```

CAS consent flow is enabled by default. You can disable the consent flow by building CAS Manager `WithConsentFlow()`:
```csharp
builder.WithConsentFlow(
    new ConsentFlow(isEnabled: false)
);
```

Don't forget to apply the configuration.
```c#
builder.Build();
```

<Error>  
You must wait until the user finishes the consent flow before you initialize third-party SDKs (such as MMPs or analytics SDKs). For this reason, initialize such SDKs from within your initialization-completion callback. If you were to initialize these third-party SDKs before the user completes the consent flow, these third-party SDKs would not be able to access relevant identifiers and you would suffer a material impact on measurement, reporting, and ad revenue.
</Error>

## Manual consent flow
Call `ShowIfRequired()` on the `ConsentFlow` class. If the consent is required, the SDK loads a form and immediately presents it . 
The `WithCompletionListener` is called after the form is dismissed. If consent is not required, the `WithCompletionListener` is called immediately. The `ConsentFlow.Status` with which the form is dismissed will be passed to the event argument.

```csharp
void Start()
{
    new ConsentFlow()
        .WithCompletionListener((status) => 
        {
            isConsentObtained = status == ConsentFlow.Status.Obtained;
        })
        .ShowIfRequired();
}
```

| ConsentFlow.Status | Description                                                        |
| ------------------ | ------------------------------------------------------------------ |
| Obtained           | User consent obtained. Personalized vs non-personalized undefined. |
| NotRequired        | User consent not required.                                         |
| Unavailable        | User consent unavailable.                                          |
| InternalError      | There was an internal error.                                       |
| InternetError      | There was an error loading data from the network                   |
| FlowStillShowing   | There was an error with another form is still being displayed      |

<Warning>  
The cache consent status on your app or a previously saved consent string, could lead to a [TCF 3.3](https://support.google.com/admanager/answer/9999955) error if consent is expired.
</Warning>

## Privacy options button
Some consent forms require the user to modify their consent at any time. Adhere to the following steps to implement a privacy options button if required.
1. Implement a UI element, such as a button in your app's settings page, that can trigger a privacy options form.
2. Once `ShowIfRequired()` completes, check `isConsentObtained` to determine whether to display the UI element that can present the privacy options form.
3. When a user interacts with your UI element, call `Show()` to show the form so the user can update their privacy options at any time.

```csharp
public Button privacyButton;

private void Start()
{
    privacyButton.onClick.AddListener(ShowPrivacyOptionsForm);
    privacyButton.interactable = isConsentObtained;
}

public void ShowPrivacyOptionsForm()
{
    new ConsentFlow()
        .WithCompletionListener((status) => 
        {
            isConsentObtained = status == ConsentFlow.Status.Obtained;
            privacyButton.interactable = isConsentObtained;
        })
        .Show();
}
```

## Debug geography
The SDK provides a way to test your app's behavior as though the device was located in the EEA or UK using the `WithDebugGeography` option. 
```c#
new ConsentFlow()
    .WithDebugGeography(ConsentFlow.DebugGeography.EEA)
    .ShowIfRequired();
```

<Info>
Note that debug geography only work if:
- Active test device defined in `CAS.settings.SetTestDeviceIds()`.
- Active Test Ad Mode in CAS Settings window.
- Active Unity Development build.
</Info>

## Inspector implementation
 Add an GameObject to your scene using `GameObject > Create Empty` in the Unity Editor. Add Component `CleverAdsSolutions/Consent Flow Ad Object` in the inspector.

<Image width="335" alt="image" src="/assets/unity/User-Consent-Flow-2.png" />

- **OnCompleted**  
The Unity event will be invoked when the Consent Flow is dismissed with one of the statuses: `Obtained`, `NotRequired`, `Unavailable`.
- **OnFailed** (String)  
The Unity event will be invoked when the Consent Flow is failed with error message.
- **EnableOptionsButton** (Boolean)   
The Unity event will be invoked to change the interactivity of the Options button for the user. Note that the real status will only be determined after calling the `showIfRequired` or initialize mobile ads. 

## Meta Audience Network Data Processing Options for Users in California
The CAS does not support your handling of CCPA opt-out values for Meta Audience Network, you must work directly with the network to  purposes of your obligations for CCPA compliance.  

To learn how to implement Meta Audience Network’s “Limited Data Use” flag, read the [Additional Meta AudienceNetwork steps](unity/additional-meta-audiencenetwork-steps).

# Custom Consent Logic
The following instructions apply if you are using your own or a third-party party consent mechanism. 

<Error>  
If you access Google demand through CAS, it’s critical that you review the [Google CMP requirements](https://support.google.com/adsense/answer/13554116) before you start the integration process.
</Error>

<Warning>  
You must set the privacy options before creating the CAS Manager to disable the automatic CAS consent flow and advertising SDKs are initialized respecting the user's consent.
</Warning>

### Request Apple App Tracking Transparency framework
Call `CAS.ATTrackingStatus.Request()` to present the app-tracking authorization request to the end user.  
We recommend waiting for the completion callback prior to initialize CAS SDK so that if the user grants the App Tracking Transparency permission, the CAS mediation can use the IDFA in ad requests.
```cs
CAS.ATTrackingStatus.Request( ( status ) =>
{
    // Tracking authorization completed. Start initialize here.
    CAS.MobileAds.BuildManager().Initialize();
    // Initialize other third-party SDKs such as MMPs or analytic
    // Do not initialize mediated advertising SDKs (CAS does that for you).
} );
```

For a better user experience, we recommend adding a **Pre permission pop-up** preceding the call to `CAS.ATTrackingStatus.Request()` to clarify the permission and data usage to users.  

### Consent in GDPR and Other regions
CAS shares these set consent values via adapters to supported mediation partners.  

If the user consents to interest-based advertising, set the user consent `Accepted` flag:
```c#
CAS.MobileAds.settings.userConsent = ConsentStatus.Accepted;
```
If the user does NOT consent to interest-based advertising, set the user consent `Denied` flag:
```c#
CAS.MobileAds.settings.userConsent = ConsentStatus.Denied;
```

Once you set the consent value, CAS will continue to respect that value for the lifetime of your application or until the user consents to interest-based advertising.

### Multi-State Consumer privacy laws
California and Virginia laws may require you to display a “Do Not Sell or Share My Personal Information” link or provide other options to users located in those states to opt out of interest-based advertising. You must set a flag that indicates whether users in those states opt out of interest-based advertising or the sale or share of personal information for interest-based advertising.

If a user does NOT opt out of interest-based advertising, set the `OptInSale` flag: 
```c#
CAS.MobileAds.settings.userCCPAStatus = CCPAStatus.OptInSale;
```
If a user does opt out of interest-based advertising, set the `OptOutSale` flag:
```c#
CAS.MobileAds.settings.userCCPAStatus = CCPAStatus.OptOutSale;
```
You do not need to set this flag for users who are outside California. If you do set this flag for such users, this will not impact how ads are served to them.
```

### Additional Meta AudienceNetwork steps

Source: https://production.docs.page/docs/unreal/additional-meta-audiencenetwork-steps

```mdx

## Data Processing Options for US Users
Meta Audience Network Data Processing Options for US Users Limited Data Use is a data processing option that gives you more control over how your data is used in Meta’s systems and better supports your compliance efforts with various US state privacy regulations. To utilize this feature, you must proactively enable Limited Data Use.  
Visit [Meta’s developer documentation](https://developers.facebook.com/docs/marketing-apis/data-processing-options) for details.

Set native the `setDataProcessingOptions` flag values:
- `ECASUserCCPAStatus::OptInSale` (`[]` empty) - To explicitly not enable Limited Data Use (LDU) mode
- `ECASUserCCPAStatus::OptOutSale` (`['LDU'], 0, 0`) - To enable LDU mode using geolocation
- `ECASUserCCPAStatus::Undefined` - Do nothing
```cpp
UCASMobileAds::SetMetaDataProcessingOptions(ECASUserCCPAStatus::OptInSale);
```
<Image width="220" alt="image" src="/assets/unreal/Additional-Meta-AudienceNetwork-steps-1.png" />

<Info>
Flag will be applied before CAS Initialization only.
</Info>

## iOS Advertising Tracking Enabled for Audience Network
Implement the [setAdvertiserTrackingEnabled](https://developers.facebook.com/docs/audience-network/setting-up/platform-setup/ios/advertising-tracking-enabled) flag, irrespective of the use of mediation, to inform Meta whether to use the data to deliver personalized ads.  

The CAS plugin will automatically pass the value from `Use Advertising Id` property in the CAS.AI Config window to native Audience Network `setAdvertiserTrackingEnabled` flag.
```

### App Open Ads

Source: https://production.docs.page/docs/unreal/app-open-ads

```mdx

App open ads are a special ad format intended for publishers wishing to monetize their app load screens.
App open ads can be closed at any time, and are designed to be shown when your users bring your app to the foreground.  
App open ads automatically show a small branding area so users know they're in your app.  

Below is a diagram showing the ad lifecycle.
<Image zoom src="/assets/Lifecycle-Screen-Ad.png" alt="Diagram" height="500" />


## Load an Ad
Call manual load ad before each show if `Autoload App Open Ads` not checked.  
In Blueprints you can use Load node just for register Loaded/Failed events.
```cpp
UCASMobileAds::LoadAppOpenAd();
```
<Image width="265" alt="Image" src="/assets/unreal/App-Open-Ads-1.png" />

<Info>
The `Event Once` checkbox will fire the Loaded/Failed event only once. if `Autoload Ads` used, events can be triggered many times while the game world exists.
</Info>

### Autoload mode
If enabled, the ad will automatically load new content when the current ad is dismissed or completed. Additionally, it will automatically retry loading the ad if an error occurs during the loading process.  

```cpp
UCASMobileAds::SetAutoloadAppOpenAd(true);
```

<Image width="237" alt="Image" src="/assets/unreal/App-Open-Ads-2.png" />

You should call `LoadAppOpenAd()` once to create Ad Instance.

By default, autoloading is defined in the `Project Settings -> Plugins -> CAS.AI Config -> Autoload App Open Ads`.

## Ad events
To further customize the behavior of your ad, you can hook into a number of events in the ad's lifecycle: loading, opening, closing, and so on. Listen for these events by registering a delegate for the appropriate event, as shown below.

```cpp
// Called when ad ready to shown.
UCASMobileAds::OnAppOpenAdLoaded.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("AppOpen loaded"));
});
// Called when ad failed to load with error.
UCASMobileAds::OnAppOpenAdLoadFailed.AddLambda([=](ECASError Error){
    UE_LOG(LogTemp, Log, TEXT("AppOpen failed to load: %s"),
        UCASMobileAds::GetAdsErrorMessage(Error));
});
// Called when the ad shown.
UCASMobileAds::OnAppOpenAdDisplayed.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("AppOpen displayed"));
});
// Called when the ad is failed to display.
UCASMobileAds::OnAppOpenAdShowFailed.AddLambda([=](ECASError Error){
    UE_LOG(LogTemp, Log, TEXT("AppOpen failed to show: %s"),
        UCASMobileAds::GetAdsErrorMessage(Error));
});
// Called when the user clicks on the Ad.
UCASMobileAds::OnAppOpenAdClicked.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("AppOpen clicked"));
});
// Called when the ad is closed.
UCASMobileAds::OnAppOpenAdDismissed.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("AppOpen dismissed"));
});
```
<Info>
Ad events in Blueprints are registered in the Load and Show nodes. Each new Load/Show Ad node cancels previous node events.
</Info>

## Show the Ad
To display the ad, call the following method:
```cpp
UCASMobileAds::ShowAppOpenAd();
```
<Image width="205" alt="Image" src="/assets/unreal/App-Open-Ads-3.png" />

### Autoshow mode
Use the `AutoshowAppOpenAd` method to automatically show the loaded ad when the user returns to the app.

```cpp
UCASMobileAds::AutoshowAppOpenAd();
```

Use the `DisableAutoshowInterstitialAd` method to disable automatically show the ad.
```cpp
UCASMobileAds::DisableAutoshowAppOpenAd();
```

<Image width="495" alt="Image" src="/assets/unreal/App-Open-Ads-4.png" />

## Release ad resource
Destroys the ad content and releases any associated resources when the ad is no longer needed to clean up resources and prevent memory leaks.

```cpp
UCASMobileAds::DestroyAppOpenAd();
```
<Image width="199" alt="Image" src="/assets/unreal/App-Open-Ads-5.png" />

Call `LoadAppOpenAd` to load new ad and restore autoload mode if used.

## Ad Availability
You can ask for the ad availability directly by calling the following function:
```cpp
bool AdLoaded = UCASMobileAds::IsAppOpenAdReady();
```
<Image width="208" alt="Image" src="/assets/unreal/App-Open-Ads-6.png" />

<Warning>  
We don’t recommend waiting for `IsAppOpenAdReady` to change each frame. This method call the native SDK and can affect the performance of your game.  
Subscribe to the `OnAppOpenAdLoaded` event instead.
</Warning>

## Muted Ads Sounds
Sounds in Interstitial and Rewarded ads mute state. Disabled by default.  
```cpp
UCASMobileAds::SetAdsMuted(Mute);
```
<Image width="134" alt="image" src="/assets/unreal/App-Open-Ads-7.png" />
```

### Banner Ads

Source: https://production.docs.page/docs/unreal/banner-ads

```mdx

Banner ad units display rectangular ads that occupy a portion of an app's layout. 
They can refresh automatically after a set period of time. 
This means users view a new ad at regular intervals, even if they stay on the same screen in your app. 
They're also the simplest ad format to implement.

Below is a diagram showing the ad lifecycle.
<Image zoom src="/assets/Lifecycle-Banner-Ad.png" alt="Diagram" height="500" />


## Get the Ad size
To load a banner ad, you need to specify the ad size. To do this, choose one of the `ECASBannerSize` from the list below:
1. **Adaptive banner** ads have a fixed aspect ratio for the maximum screen width. The adaptive size calculates the optimal height for that width with an aspect ratio similar to 320x50.
```cpp
ECASBannerSize adSize = ECASBannerSize::Adaptive;
```
2. **Smart ad size** selects the optimal dimensions depending on the device type. For mobile devices, it returns 320x50, while for tablets, it returns 728x90. In the UI, these banners occupy the same amount of space regardless of device type.
```cpp
ECASBannerSize adSize = ECASBannerSize::Smart;
```
3. **Leaderboard** has a fixed size of 728x90 and is allowed on tablets only.
```cpp
ECASBannerSize adSize = ECASBannerSize::Leaderboard;
```
4. **Standard banner** has a fixed size of 320x50 and is the minimum ad size.
```cpp
ECASBannerSize adSize = ECASBannerSize::Banner;
```

## Load an Ad
Call manual load ad before each show if `Autoload Banner Ads` not checked.  
In Blueprints you can use Load node just for register Loaded/Failed events.
```cpp
UCASMobileAds::LoadBannerAd(adSize);
```
<Image width="240" alt="image" src="/assets/unreal/Banner-Ads-1.png" />

<Info>
The `Event Once` checkbox will fire the Loaded/Failed event only once. if `Autoload Ads` used, events can be triggered many times while the game world exists.
</Info>

### Autoload mode
If enabled, the ad will automatically load new content when the current ad is dismissed or completed. Additionally, it will automatically retry loading the ad if an error occurs during the loading process.  

```cpp
UCASMobileAds::SetAutoloadBannerAd(true);
```

<Image width="221" alt="Image" src="/assets/unreal/Banner-Ads-2.png" />

You should call `LoadBannerAd()` once to create Ad Instance.

By default, autoloading is defined in the `Project Settings -> Plugins -> CAS.AI Config -> Autoload Banner Ads`.

## Display the Ad
When you are ready to show the ad on the screen, just call the following method:
```cpp
UCASMobileAds::ShowBannerAd();
```
When you need to hide the ad from the user, just call the following method:
```cpp
UCASMobileAds::HideBannerAd();
```
<Image width="310" alt="image" src="/assets/unreal/Banner-Ads-3.png" />

<Info>
You can change the banner's activity even if it is not ready to be shown yet. When the ad is ready, banner will shown automatically.
</Info>

## Ad events
To further customize the behavior of your ad, you can hook into a number of events in the ad's lifecycle: loading, opening, closing, and so on. Listen for these events by registering a delegate for the appropriate event, as shown below.

```cpp
// Called when the ad loaded and ready to present.
UCASMobileAds::OnBannerAdLoaded.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("Banner loaded"));
});
// Сalled when an error occurred with the ad.
UCASMobileAds::OnBannerAdFailed.AddLambda([=](ECASError Error){
    UE_LOG(LogTemp, Log, TEXT("Banner failed to load: %s"),
        UCASMobileAds::GetAdsErrorMessage(Error));
});
// Called when the user clicks on the Ad.
UCASMobileAds::OnBannerAdClicked.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("Banner clicked"));
});
```
<Info>
Ad events in Blueprints are registered in the Load nodes. Each new Load Ad node cancels previous node events.
</Info>

## Ad position
The position where the banner ad should be placed. The `ECASPosition` enum lists the valid ad position values.  
By default, the banner ad is centered at the bottom.  
Changing the position of a banner ad **does not destroy** the current banner or load a new one.  

Change the banner position on screen using the following method:
```cpp
UCASMobileAds::SetBannerAdPosition(ECASPosition::TopCenter);
```
<Image width="255" alt="image" src="/assets/unreal/Banner-Ads-4.png" />

## Ad Refresh rate
An ad unit’s automatic refresh rate (in seconds) determines how often a new ad request is generated for that ad unit.  
We recommended using refresh rate 30 seconds. However, you can choose any value you want. Or set 0 to disable automatic refresh ads.

Change the banner automatic refresh rate using the following method:
```cpp
UCASMobileAds::SetBannerAdRefreshInterval(RefreshIntervalInSeconds);
```
<Image width="217" alt="image" src="/assets/unreal/Banner-Ads-5.png" />

<Info>
- Ad requests should not be made when the device screen is turned off.  
- The `setAutoloadBannerAd()` has no effect on refreshing the banner ad.
</Info>

## Release ad resource
Destroys the ad content and releases any associated resources when the ad is no longer needed to clean up resources and prevent memory leaks.

```cpp
UCASMobileAds::DestroyBannerAd();
```
<Image width="147" alt="image" src="/assets/unreal/Banner-Ads-6.png" />

Call `LoadBannerAd` to load new ad and restore autoload mode if used.

## Ad Availability
You can ask for the ad availability directly by calling the following function:
```cpp
bool BannerLoaded = UCASMobileAds::IsBannerAdReady();
```
<Image width="159" alt="image" src="/assets/unreal/Banner-Ads-7.png" />

<Warning>  
We don’t recommend waiting for `IsBannerAdReady` to change each frame. This property call the native SDK and can affect the performance of your game. Subscribe to the `OnBannerAdLoaded` event instead.
</Warning>
```

### Building Unreal Engine 4 with XCode 14

Source: https://production.docs.page/docs/unreal/building-unreal-engine-4-with-xcode-14

```mdx

In order to implement CAS plugin and package project for iOS, you will need XCode 14. Unreal Engine 4 does not support XCode 14 by default, so you must do some changes to its code.

## Download sources

First, you will need Unreal Engine from GitHub. To finish this step, please, refer to official documentation: 

https://docs.unrealengine.com/4.27/en-US/ProgrammingAndScripting/ProgrammingWithCPP/DownloadingSourceCode/

> Make sure you clone needed version of UE4 from certain tag, not from a main/master branch. 
> 
> For example `git clone --depth 1 --branch 4.27.2-release git@github.com:EpicGames/UnrealEngine.git`

## Fix Unreal Engine 4 for XCode 14

Unreal Engine 4 generates XCode project by its build system. XCode project gets generates with some options missing. We need to add those in order to make UE4 compile successfully.

In files 

1) Engine/Source/Programs/UnrealBuildTool/Platform/Mac/MacToolChain.cs
2) Engine/Source/Programs/UnrealBuildTool/Platform/IOS/IOSToolChain.cs

Add following lines in function `GetCompileArguments_Global`:

```cs
// Add after line 
// Result += " -Wall -Werror"; 
// next lines

Result += " -Wno-unused-but-set-variable";
Result += " -Wno-uninitialized-const-reference";
Result += " -Wno-ordered-compare-function-pointers";
```


You will also need to do a little fix in `Engine/Source/ThirdParty/libWebSockets/libwebsockets/include/Mac/libwebsockets.h`.

```cpp
// Replace line
enum http_status {
//With
enum class http_status {
```
```

### Configuring SDK

Source: https://production.docs.page/docs/unreal/configuring-sdk

```mdx

In your Unreal project editor, navigate to `Edit > Project Settings > Plugins > CAS.AI Config - [Platform]` to modify default configuration for each native platform.  

<Image width="650" alt="image" src="/assets/unreal/Configuring-SDK-1.png" />

<Info>
Repeat the following steps for Android and iOS platforms.
</Info>

## CAS App ID
In most cases, a CAS App Id is the same as the Android App's package name, and the iOS App's store Id.
- A [package name](https://developer.android.com/studio/build/application-id) uniquely identifies your app on the device and in the Google Play Store.
- The store ID of an iOS app uniquely identifies your app in the Apple App Store.
- You can find an app's store ID in the URL of your app’s Apple App Store listing. For example, the URL of an app page is `apps.apple.com/us/app/id123456789`. The app's store ID is `123456789`.
-  If you haven't created an CAS account and registered an app yet, now's a great time to do so at [CAS.ai](https://cas.ai). 
- In a real app, it is important that you use your actual CAS App ID.  

## Autoload ad formats
Select the advertisement formats that will be loaded automatically after the ads initialization. The chosen ad formats will also be automatically loaded after being displayed or encountering a loading error. In this case, you may choose not to use the ad loading functions and instead simply call the ad display functions when needed. The ad will be displayed if it is ready; otherwise, a failure event will be triggered.
- [x]  Autoload Banner Ads
- [x]  Autoload MRec Ads
- [x]  Autoload Interstitial Ads
- [x]  Autoload Rewarded Ads
- [x]  Autoload App Open Ads

<Warning>  
Do not select ad formats that you do not intend to show to the user, as it will impact the performance of the application.
</Warning>

## Enabling test ads
Read about Test ads mode and Test Device Ids [here](enabling-test-ads).
- [x] TestAdsMode

## Target app audience
Select the audience your game is targeting.  
- Mixed - The app is intended for audiences of all ages.
- Children - Children restrictions and Google Families Ads Program participation apply to this app. Audience under 12 years old.
- NotChildren - Audience over 12 years old only. There are no restrictions on ad filling.  

<Success>  
Read more about [COPPA compliance](privacy-regulations).
</Success>

## Auto Consent Flow
Select to automatic ask for consent from the user on ads initialization. To get consent for collecting personal data of your users, we suggest you use a built-in Consent Flow, comes with a pre-made consent form that you can easily present to your users.
- [x] Auto Consent Flow

<Success>  
Read more about [User Consent Flow](user-consent-flow).
</Success>

## Use Advertising Id
The Advertising ID is a unique, user-resettable ID for advertising, provided by Google Play services ([AD_ID](https://support.google.com/googleplay/android-developer/answer/6048248?hl=en)) or by Apple ([IDFA](https://developer.apple.com/documentation/adsupport/asidentifiermanager/advertisingidentifier)). Crucial for mobile attribution, i.e. tracking the user journey, its purpose is to measure user interactions with ad campaigns and track events like installs and in-app activity.
- [x] Use Advertising Id

## User Tracking Usage Description (iOS Only)
If your app calls the App Tracking Transparency API, you must provide custom text, known as a _usage-description string_, which displays as a system-permission alert request. The usage-description string tells the user why the app is requesting permission to use data for tracking the user or the device. The user has the option to grant or deny the authorization request.
<Success>  
- Allowed if used Advertising Id property only.
- Read more about [NSUserTrackingUsageDescription](https://developer.apple.com/documentation/bundleresources/information_property_list/nsusertrackingusagedescription)
</Success>

## Privacy Policy URL
Provide a link to the app's Privacy Policy so that it is presented to the user in the consent dialog.

<Info>
If you don't define a link to your application's policy, the user will follow the link to [Clever Ads Solutions policy](https://cas.ai/privacy-policy-3/).
</Info>

## Include Ads Solution
<Warning>
CAS.AI is a mediation SDK with no built-in live ad inventory. At least one ad network adapter or solution must be integrated before publishing to display ads and generate revenue.
</Warning>

Clever Ads Solutions provide ready-made solutions for you to choose from.
- [ ] An **Optimal Ads Solutions** contains a number of stable partner networks that are recommended for use in most applications.  
- [ ] A **Families Ads Solutions** designed for applications tagged at a children's audience.  
  - For Android, solution is fully compatible with apps in the [Google Plays Families Policy](unreal/google-plays-families-policy).
  - For iOS, solution is NOT intended for apps in [Apple Kids Category](general/apple-kids-category).

<Warning>  
Some ad networks require you to do Additional integration steps: [Meta AudienceNetwork](unreal/additional-meta-audiencenetwork-steps)
</Warning>

## Advanced Integration
Advanced integration makes it possible to choose any variations of mediation networks.
Feel free not to use ready-made solutions, and choose which mediated ad networks you want to integrate by checking the boxes in `Mediation/Advanced` section of settings window.

<Info>  
Access to the monetization of the `beta` ad sources is closed.  
If you would like to monetize by one of these ad sources, please contact your account manager.
</Info>

## Cross-promotion
Cross-promotion is an app marketing strategy in which app developers promote one of their titles on another one of their titles. Cross promoting is especially effective for developers with large portfolios of games as a means to move users across titles and use the opportunity to scale each of their apps. This is most commonly used by hyper-casual publishers who have relatively low retention, and use cross promotion to keep users within their app portfolio.  

Start your cross promotion campaign with https://cas.ai.  

<Info>
CrossPromotion can be installed/removed using `Mediation/Advanced` section.
</Info>
```

### Enabling test ads

Source: https://production.docs.page/docs/unreal/enabling-test-ads

```mdx

This guide explains how to enable test ads in your ads integration. It's important to enable test ads during development so that you can click on them without charging CAS advertisers.

<Error>  
We strongly suggest that you enable test ads mode when you validate the integration.  If you click on too many ads without being in test mode, you risk your account being flagged for invalid activity.
</Error>

There are two ways to get test ads:
- [Enable test ad mode](unreal/enabling-test-ads#enable-test-ad-mode) for all devices.
- [Set device ids to test ad](unreal/enabling-test-ads#enable-test-devices).

Ads with Test Ads mode are safe to click. Requests, impressions, and clicks on test ads will not show up in your account's reports.  
Test full-screen ads displays details of CAS integration and tips for solving errors. Go to the Mediation Adapters section to make sure that the advertising networks you want are integrated correctly.

<Image height="500" alt="image" src="/assets/Enabling-test-ads-1.jpg" />
<Image height="500" alt="image" src="/assets/Enabling-test-ads-2.jpg" />

## Enable test ad mode
The quickest way to enable testing is to use test ad mode. The test ad mode are not associated with your CAS account, so there's no risk of your account generating invalid traffic when using these test ad mode.

1. In your Unity project, navigate to `Edit > Project Settings > Plugins > CAS.AI Config - [Platform]` to create and modify default settings for each native platform.
2. Enable Test Ad mode.
3. Use any no empty Manager ID. For example `demo` or your CAS Manager ID.

<Image width="650" alt="image" src="/assets/unreal/Enabling-test-ads-3.png" />

<Warning>  
Make sure you disable test ad mode and replace test App ID with your own ad CAS ID before publishing your app!
</Warning>

## Enable test devices
If you want to do more rigorous testing with production-looking ads, you can now configure your device as a test device and use your own manager id. Test devices can either be added programmatically.

Follow the steps below to add your device as a test device.
1. Run an app configured with the CAS on device.
2. Check the console or logcat output for a message that looks like this:
```
To get test ads on this device, set "12345678901234567890123456789012"
```
3. Copy your alphanumeric test device ID to your clipboard.
4. Modify project settings to set the test device ID.

<Info>
Be sure to remove the test devices before you release your app.
</Info>

5. Re-run your app. 
6. Well done, ads on this device are safe to click. Requests, impressions, and clicks on ads in test mode will not show up in your account's reports.
```

### FAQ

Source: https://production.docs.page/docs/unreal/faq

```mdx

## iOS Crash on app launch
If you're getting a crash on app launch with the following symbols, it means the CAS Unreal Plugin failed to add the Google App ID to your app's Info.plist for some reason. 
```
0x0000000103348aac GADForwardedUserDefaults + 484
0x0000000103330270 GADApplicationVerifyPublisherInitializedCorrectly + 2660
```

You should share the build details of your app with your account manager. If the automation issue can't be resolved, the manager will provide an identifier that you'll need to add to your `Config/DefaultEngine.ini` file in the following format.
```ini
[CASPluginBuildConfig]
GoogleAppIdIOS=ca-app-pub-0000000000000000~0000000000
```

## iOS Build failed
### ARM64 branch out of range (-135091044 max is +/-128MB)
The error message "ARM64 branch out of range" indicates that a branch instruction in your code is attempting to jump to a location that is too far away, and it exceeds the allowed range.

This is due to the large size of the Pangle library. You can choose one of the following solutions:
- Enable "Packaging For Distribution" in the project settings. This will activate the necessary code optimizations, and packaging will be successful.
- Exclude the Pangle Ad Adapter from the build. We recommend excluding all adapters during development and activating the ad test mode. This will speed up the build time and allow for proper ad testing in the application.
### Undefined symbols for architecture arm64
```
__swift_FORCE_LOAD_$_swiftCompatibility56", referenced from:
  __swift_FORCE_LOAD_$_swiftCompatibility56_$_CleverAdsSolutions in CleverAdsSolutions
  ...
  (maybe you meant: __swift_FORCE_LOAD_$_swiftCompatibility56_$_CleverAdsSolutions)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1
```
This error occurs because your Xcode version lacks the necessary Swift components. Please check the Xcode version requirements and update it accordingly.
### Duplicate symbols for architecture arm64
```
duplicate symbol '_OBJC_IVAR_$_FBLPromise._pendingObjects' in:
.../UnzippedFrameworks/PromisesObjC/PromisesObjC.framework/PromisesObjC(FBLPromise.o)
.../CAS-Unreal-main/Source/ThirdParty/IOS/Frameworks/FBLPromises/FBLPromises.framework/FBLPromises(FBLPromise.o)
...
ld: 12 duplicate symbols for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
```
You need to exclude iOS frameworks from the CAS Plugin that have already been added by other plugins in your project. To do this, modify the `Config/DefaultEngine.ini` file of the project by adding the `[CASPluginBuildConfig]` section. For example, excluding the `FBLPromises.framework`, which has been added to the Firebase plugin project, is represented as follows:
```ini
[CASPluginBuildConfig]
+ExcludeFrameworks="FBLPromises"
```

## Android Build failed
### AAPT: error: unexpected element `<property>` found in `<manifest><application>`.
Google AdMob updated its SDK to require Android Gradle plugin version 4.2.0 or higher and Gradle version 6.7.1 or higher. Update your Android Gradle plugin and Gradle versions to resolve error.

### AAPT2 Unexpected error during link, attempting to stop daemon
```
* What went wrong:
Execution failed for task ':launcher:processReleaseResources'.
> A failure occurred while executing com.android.build.gradle.internal.res.LinkApplicationAndroidResourcesTask$TaskAction
   > AAPT2 aapt2-4.2.2-7147631-osx Daemon #0: Unexpected error during link, attempting to stop daemon.
     This should not happen under normal circumstances, please file an issue if it does.
```
Usually, the AAPT2 error occurs when a project is built with Target Android SDK 34 and the SDK Build Tools version is below 34.0.0, because one of the dependencies libraries uses new AAPT2 features that are not available in Build Tools versions below 34.  

We are aware that the DTExchange library is causing this issue.

To resolve this problem, you need to override the AAPT2 path in `gradle.properties` from the Build Tools 34.0.0.
1. Download AAPT2. 
Download Build-Tools 34.0.0 via Android SDK Manager or obtain just the [AAPT2 component from Google Maven](https://developer.android.com/tools/aapt2#download_aapt2).
2. Move the downloaded directory from the Android SDK so that UE does not use Build-Tools version 34 for compilation. 
3. Override Gradle path to AAPT2
Add the following line in any Android UPL file:
```xml
<gradleProperties>
	<insert>
android.aapt2FromMavenOverride=/full/path/to/build-tools/34.0.0/aapt2
	</insert>
</gradleProperties>
```
Replace `/full/path/to/build-tools` with the actual path to downloaded directory.  
For Windows use file with extension: `appt2.exe`.
```

### Google Plays Families Policy

Source: https://production.docs.page/docs/unreal/google-plays-families-policy

```mdx

<Info>
If your application does not participate in Families Ads program, then you can safely skip the page. 
</Info>

Google is focused on providing a great experience for families on Google Play and wants to help make sure that any ads served to children are appropriate and compliant with our policies. Review google ads and monetization policy in the [Developer Policy Center](https://play.google.com/about/families/ads-monetization/).  

If your app's target audience includes children and serves ads using an ad SDK, you must use one of the ad SDKs below. The following ad SDKs have self-certified that their compliance with Play’s [Families Ads Program](https://play.google.com/about/monetization-ads/families-ads-program/) requirements.

> ❕Quote from the [Google Families Ads program page](https://support.google.com/googleplay/android-developer/answer/9283445?hl=en).

### Advertising ID
The [advertising ID](https://support.google.com/googleplay/android-developer/answer/6048248?hl=en) is a unique, user-resettable ID for advertising, provided by Google Play services.  

With Android 12 many mediation partners are starting to include the `com.google.android.gms.permission.AD_ID` permission in the SDK’s library manifest but Families Policy, require that apps not use the Ad ID.  
You must prevent the permission from getting merged into your app by including the following element in your manifest.  

Navigate `Edit > Project Settings > Plugins > CAS.AI Config - Android` window and uncheck property:
 - [ ]  Use Advertiser Id
```

### Impression Level Data

Source: https://production.docs.page/docs/unreal/impression-level-data

```mdx

CAS.AI enables you to access detailed information for each impression through the impressions callback APIs. The information includes, for example, which demand source served the ad, the expected or exact revenue associated with it. In addition, it contains granular details to allow you to analyze and, ultimately, optimize user acquisition strategies. 

## Ad Impression
`FCASImpressionInfo` is an struct for getting detailed information about the current ad impression, such as revenue and ad creative details.  

```cpp

UCASMobileAds::OnAdsImpression.AddLambda([=](const FCASImpressionInfo& info){
    // Get ad details using info parameter
});
```
<Image width="468" alt="image" src="/assets/unreal/Impression-Level-Data-1.png" />

### Ad revenue
The revenue generated for the 1000 impressions in USD. 
```cpp
float cpm = info.RevenueCPM;
```

### Ad creative
You can also retrieve information about the current ad (such as its mediated network and creative ID), and you will be able to report creative issues for that ad to our Ad review team.
```cpp
FString PlacementType = info.PlacementType;
FString CreativeId = info.CreativeID;
FString NetworkName = info.Network;
FString NetworkUnitId = info.UnitID;
```
### User ad summary 
CAS count the number of ad impressions and the total revenue of all formats at the time of a new impression. 
```cpp
int totalImpressions = info.TotalImpressions;
float totalRevenue = info.LifetimeRevenue;
```

<Info>
Progress is saved between sessions until the user clears your app's data.
</Info>

## Automatic collect ad revenue
The CAS SDK have features to automatically collect ad revenue to Google Analytics and Tenjin Analytics. Contact your account manager for details of enabling automatic events.
#### Google Analytics
If you haven't already, make sure to complete the following tasks:
1. Set up your project and app as described in [Get Started with Analytics](https://firebase.google.com/docs/analytics/get-started).
2. Make sure that you've linked your Firebase project to a Google Analytics account.
3. Ensure that you've included in your app the CAS SDK 3.5.0+.

To measure ad revenue, CAS SDK log [`ad_impression` events](https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#public-static-final-string-ad_impression) whenever your user sees an advertisement in your app. These events contain details such as the ad platform, source, currency, and value. Optionally, the alternative event name can be `CAS_Impression`.  

#### Tenjin
If you haven't already, make sure to complete the following tasks:
1. Set up your project and app as described in [Get Started with Analytics](https://docs.tenjin.com/docs/android-sdk#basic-integration).
2. Make sure that you've [initialize tenjin session](https://docs.tenjin.com/docs/android-sdk#app-initialization).
3. Ensure that you've included in your app the CAS SDK 3.7.2+.
```

### Include Android

Source: https://production.docs.page/docs/unreal/include-android

```mdx

## Disable Unreal Engine's built-in AdMob support
The CAS plugin automatically performs all configurations for AdMob in mediation integration.  

Navigate to the `Editor > Project Settings > Platform > Android > Google Play Services` section and disable the option:
 - [ ] Include AdMob support for ads

Additionally, use the advertising management functions from CAS Mobile Ads, not the built-in functions for AdMob. 

<Warning>  
Be cautious, as some Blueprint Nodes have identical names: `Show Interstitial Ad`, `Show Ad Banner`.  
You should exclusively use nodes from the CAS Mobile Ads category.
</Warning>

## Upgrade the Gradle wrapper
To select the Gradle version, navigate to the directory for your version of the Unreal Engine and follow the file path.
```
Engine/Build/Android/Java/gradle/gradle/wrapper/gradle-wrapper.properties
```
Change the `distributionUrl` property to the desired version.
```
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-all.zip
```

<Info>
If your UE is already using a newer version of Gradle than 6.7.1, you don't need to do anything further. The Android Gradle plugin version will also be at least 4.2.2.
</Info>

## Upgrade the Android Gradle plugin
To select the Android Gradle plugin version, navigate to the directory for your version of the Unreal Engine and follow the file path.
```
Engine/Build/Android/Java/gradle/build.gradle
```
Change the line with `com.android.tools.build:gradle` to the desired version.
```gradle
buildscript {
    repositories { ... }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.2.2'
    }
    ...
}
```

## Unreal Engine 4 compatibility for API 34
The AppCache API is no longer supported, so its use must be removed from the engine java script.  

Navigate to the directory for your version of the Unreal Engine and follow the file path.
```
Engine/Build/Android/Java/src/com/epicgames/ue4/WebViewControl.java
```
Remove (comment) the following lines of code:
```java
viewer.getSettings().setAppCacheMaxSize(1024*1024*8);
viewer.getSettings().setAppCachePath("/data/data/com.your.package.appname/cache"‌​);
viewer.getSettings().setAppCacheEnabled(true);
```

## Unreal Engine 4 compatibility for API 32
Applications which has an activity, activity alias, service or broadcast receiver with intent filter, must explicitly declare the `android:exported` attribute.  

Navigate to the `Editor > Project Settings > Platform > Android > Advanced APK Packaging` section and add `Extra Tags for UE4 GameActivity <activity> node`:
```
android:exported="true"
```
```

### Include iOS

Source: https://production.docs.page/docs/unreal/include-ios

```mdx

<Info>
When changing the included adapter set, you will also need to delete the `Project/Binaries/IOS` folder to reset the cache of previous application builds
</Info>

## Install CocoaPods
iOS dependencies are identified using  [CocoaPods](https://guides.cocoapods.org/using/getting-started.html).  
Make sure that CocoaPods is installed called terminal command:
```sh
pod --version
```
Install if not found command to Homebrew:
```sh
brew install cocoapods
```
Or RubyGems:
```sh
sudo gem install cocoapods
```

The CAS plugin will **automatically integrate third-party frameworks** and resource bundles from the CocoaPods repository for the selected ad networks in the CAS Config window before packaging the application.

## Disable Bitcode
Building with bitcode is no longer supported. [Apple deprecated Bitcode](https://developer.apple.com/documentation/Xcode-Release-Notes/xcode-14-release-notes) in Xcode 14.  
You should disable Bitcode by navigating to `Edit > Project Settings > Platforms > iOS` section.

<Info>
Starting from version 5.2, Unreal Engine no longer utilizes Bitcode in iOS builds.  
</Info>

## SKAdNetwork
SKAdNetwork is a privacy safe method provided by Apple for ad networks to track installs. Up until iOS 14, most ad network campaign attribution has been based on a user's IDFA, but on iOS 14 and beyond, IDFAs will be less usable as a way to attribute which users have installed based on which ads they have interacted with.

The CAS Unreal Plugin **automatically updates** your app’s `Info.plist` with network-specific identifiers.

<Info>
To learn why these identifiers matter and what you lose without them, see [Apple Ad Attribution](general/apple-ad-attribution).
</Info>

## Exclude Frameworks
Sometimes when multiple different plugins are used in a project, they may utilize the same frameworks. Each plugin will package its own version of frameworks, which can lead to issues during code linking. You will need to decide which frameworks should remain in the package and which ones need to be excluded.  
To exclude frameworks required for the CAS Plugin, utilize the `Config/DefaultEngine.ini` file in your project. Add the following lines to the file with the names of the frameworks that need to be excluded from the package.
```ini
[CASPluginBuildConfig]
+ExcludeFrameworks="Framework1NameWitoutExtension"
+ExcludeFrameworks="Framework2NameWitoutExtension"
```

<Info>
Be cautious, although you can exclude frameworks from the package, the package will not build if the referenced code is not found.
</Info>

## Unreal Engine 4 compatibility for XCode (Apple clang) 15
The Clang 15 update introduced some compilation flags. You need to disable these new flags to ensure that Unreal Engine 4 code remains compatible and compiles without errors.

Open the files of your project `Source/ProjectName.Target.cs` and `Source/ProjectNameEditor.Target.cs` and add the following lines to the constructor of the class.
```csharp
if (Target.Platform == UnrealTargetPlatform.Mac || Target.Platform == UnrealTargetPlatform.IOS)
{
	bOverrideBuildEnvironment = true;
	// Xcode 15
	AdditionalCompilerArguments += " -Wno-deprecated-builtins";
	AdditionalCompilerArguments += " -Wno-error=single-bit-bitfield-constant-conversion";

	// Xcode 14
	AdditionalCompilerArguments += " -Wno-error=bitwise-instead-of-logical";
	AdditionalCompilerArguments += " -Wno-error=deprecated-declarations";
	AdditionalCompilerArguments += " -Wno-error=unqualified-std-cast-call";
	AdditionalCompilerArguments += " -Wno-error=unused-but-set-variable";
}
```
```

### Initialize CAS SDK

Source: https://production.docs.page/docs/unreal/initialize-cas

```mdx

To display ads, you must initialize the Mobile Ads once, ideally at app launch.  

```cpp
#include "CASMobileAds.h"

UCASMobileAds::OnAdsInitialized.AddLambda([this](const FCASInitialConfig &Config) {
    if (Config.Error.IsEmpty()) {
        // Ads initialization completed
    } else {
        // Ads initialization failed with Config.Error
    }
    // The CAS SDK initializes if the error IsEmpty()
    FString InitErrorOrEmpty = Config.getError;
    FString UserCountryISO2OrEmpty = Config.CountryCode;
    
    // The user completes the consent flow
    ECASConsentFlowStatus ConsentFlowStatus = Config.ConsentFlowStatus; 
});

UCASMobileAds::InitializeMobileAds();
```
<Image width="271" alt="image" src="/assets/unreal/Initialize-CAS-1.png" />

The `OnAdsInitialized` event may be called with an error. In this case, the SDK will attempt to reinitialize and the listener will be called again until the error is resolved.

## Check initialized ads
You can also check whenever CAS was initialized. Use `IsInitializedAds` if you are unsure before using ad interfaces or want to do additional checks.
```cpp
UCASMobileAds::IsInitializedAds();
```

<Image width="144" alt="image" src="/assets/unreal/Initialize-CAS-2.png" />

## Retrieve the Version Number
To programmatically retrieve the SDK version number at runtime, the plugin provides the following method:
```cpp
UCASMobileAds::GetMobileAdsVersion();
```

<Image width="178" alt="image" src="/assets/unreal/Initialize-CAS-3.png" />

## (Optional) Trial ad-free interval
Set the time interval during which users can enjoy an ad-free experience while retaining access
to Rewarded Ads and App Open Ads formats. This interval is defined from the moment of the initial
app installation, in seconds. Within this interval, users enjoy privileged access to the
application's features without intrusive advertisements.

```cpp
int SecondsIn7Days = 604800;
UCASMobileAds::SetTrialAdFreeInterval(secondsIn7Days);
```
<Image width="185" alt="image" src="/assets/unreal/Initialize-CAS-4.png" />
```

### Interstitial Ads

Source: https://production.docs.page/docs/unreal/interstitial-ads

```mdx

Interstitial ads are full-screen ads that cover the interface of their host app. 
They're typically displayed at natural transition points in the flow of an app, such as between screens or during the pause between levels in a game. 
When an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.  

Below is a diagram showing the ad lifecycle.
<Image zoom src="/assets/Lifecycle-Screen-Ad.png" alt="Diagram" height="500" />


## Load an Ad
Call manual load ad before each show if `Autoload Interstitial Ads` not checked.  
In Blueprints you can use Load node just for register Loaded/Failed events.
```cpp
UCASMobileAds::LoadInterstitialAd();
```
<Image width="235" alt="image" src="/assets/unreal/Interstitial-Ads-1.png" />

<Info>
The `Event Once` checkbox will fire the Loaded/Failed event only once. if `Autoload Ads` used, events can be triggered many times while the game world exists.
</Info>

### Autoload mode
If enabled, the ad will automatically load new content when the current ad is dismissed or completed. Additionally, it will automatically retry loading the ad if an error occurs during the loading process.  

```cpp
UCASMobileAds::SetAutoloadInterstitialAd(true);
```

<Image width="211" alt="Image" src="/assets/unreal/Interstitial-Ads-2.png" />

You should call `LoadInterstitialAd()` once to create Ad Instance.

By default, autoloading is defined in the `Project Settings -> Plugins -> CAS.AI Config -> Autoload Interstitial Ads`.

## Ad events
To further customize the behavior of your ad, you can hook into a number of events in the ad's lifecycle: loading, opening, closing, and so on. Listen for these events by registering a delegate for the appropriate event, as shown below.

```cpp
// Called when ad ready to shown.
UCASMobileAds::OnInterstitialAdLoaded.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("Interstitial loaded"));
});
// Called when ad failed to load with error.
UCASMobileAds::OnInterstitialAdLoadFailed.AddLambda([=](ECASError Error){
    UE_LOG(LogTemp, Log, TEXT("Interstitial failed to load: %s"),
        UCASMobileAds::GetAdsErrorMessage(Error));
});
// Called when the ad shown.
UCASMobileAds::OnInterstitialAdDisplayed.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("Interstitial displayed"));
});
// Called when the ad is failed to display.
UCASMobileAds::OnInterstitialAdShowFailed.AddLambda([=](ECASError Error){
    UE_LOG(LogTemp, Log, TEXT("Interstitial failed to show: %s"),
        UCASMobileAds::GetAdsErrorMessage(Error));
});
// Called when the user clicks on the Ad.
UCASMobileAds::OnInterstitialAdClicked.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("Interstitial clicked"));
});
// Called when the ad is closed.
UCASMobileAds::OnInterstitialAdDismissed.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("Interstitial dismissed"));
});
```
<Info>
Ad events in Blueprints are registered in the Load and Show nodes. Each new Load/Show Ad node cancels previous node events.
</Info>

## Show the Ad
To display the ad, call the following method:
```cpp
UCASMobileAds::ShowInterstitialAd();
```
<Image width="177" alt="image" src="/assets/unreal/Interstitial-Ads-3.png" />

### Autoshow mode
Use the `AutoshowInterstitialAd` method to automatically show the loaded ad when the user returns to the app.

```cpp
UCASMobileAds::AutoshowInterstitialAd();
```

Use the `DisableAutoshowInterstitialAd` method to disable automatically show the ad.
```cpp
UCASMobileAds::DisableAutoshowInterstitialAd();
```

<Image width="497" alt="Image" src="/assets/unreal/Interstitial-Ads-4.png" />

## Release ad resource
Destroys the ad content and releases any associated resources when the ad is no longer needed to clean up resources and prevent memory leaks.

```cpp
UCASMobileAds::DestroyInterstitialAd();
```
<Image width="207" alt="Image" src="/assets/unreal/Interstitial-Ads-5.png" />

Call `LoadInterstitialAd` to load new ad and restore autoload mode if used.

## Ad Availability
You can ask for the ad availability directly by calling the following function:
```cpp
bool AdLoaded = UCASMobileAds::IsInterstitialAdReady();
```
<Image width="179" alt="image" src="/assets/unreal/Interstitial-Ads-6.png" />

<Warning>  
We don’t recommend waiting for `IsInterstitialAdReady` to change each frame. This method call the native SDK and can affect the performance of your game.  
Subscribe to the `OnInterstitialAdLoaded` event instead.
</Warning>

## Minimum interval between impressions
You can limit the posting of an interstitial ad to a period of time in seconds after the ad is closed, during which display attempts will fail.
That the interval starts only after the Interstitial Ad **closes** `OnInterstitialAdDismissed`.  
During interval after ad closed, display attempts will fire event `OnInterstitialAdShowFailed` with `ECASError::IntervalNotYetPassed`.  

Change the interstitial ad impression interval using the following method:
```cpp
UCASMobileAds::SetInterstitialAdMinimumInterval(Interval);
```
<Image width="248" alt="image" src="/assets/unreal/Interstitial-Ads-7.png" />

If you need to wait for a period of time after the start of the game or after showing a Rewarded Ad until next Interstitial Ad impression then please call the following method:
```cpp
UCASMobileAds::RestartInterstitialAdInterval();
```
<Image width="213" alt="image" src="/assets/unreal/Interstitial-Ads-8.png" />

<Info>
We recommend define the interstitial ad impression interval once before mediation manager is initialized to be able to override the value remotely via the web interface.
</Info>

## Muted Ads Sounds
Sounds in Interstitial and Rewarded ads mute state. Disabled by default.  
```cpp
UCASMobileAds::SetAdsMuted(Mute);
```
<Image width="134" alt="image" src="/assets/unreal/Interstitial-Ads-9.png" />

## Some best practices
- **Consider whether interstitial ads are the right type of ad for your app.**  
Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, such as sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it's easy to present an interstitial ad without disrupting their experience. Make sure you consider at which points in your app's workflow you'll display interstitial ads and how the user is likely to respond.  
- **Remember to pause the action when displaying an interstitial ad.**  
There are a number of different types of interstitial ads: text, image, video, and more. It's important to make sure that when your app displays an interstitial ad, it also suspends its use of some resources to allow the ad to take advantage of them. For example, when you make the call to display an interstitial ad, be sure to pause any audio output being produced by your app. You can resume playing sounds in the `OnInterstitialAdClosed` event handler, which will be invoked when the user has finished interacting with the ad. In addition, consider temporarily halting any intense computation tasks (such as a game loop) while the ad is being displayed. This will make sure the user doesn't experience slow or unresponsive graphics or stuttered video.
- **Don't flood the user with ads.**  
While increasing the frequency of interstitial ads in your app might seem like a great way to increase revenue, it can also degrade the user experience and lower clickthrough rates. Make sure that users aren't so frequently interrupted that they're no longer able to enjoy the use of your app.
```

### Medium Rectangle Banner Ads

Source: https://production.docs.page/docs/unreal/mrec-ads

```mdx

Medium Rectangle (MREC) are rectangular image or text ads that occupy a spot with size in dp (300x250) on screen. 
They stay on screen while users are interacting with the app, and can refresh automatically after a certain period of time. 

Below is a diagram showing the ad lifecycle.
<Image zoom src="/assets/Lifecycle-Banner-Ad.png" alt="Diagram" height="500" />


## Load an Ad
Call manual load ad before each show if `Autoload MRec Ads` not checked.  
In Blueprints you can use Load node just for register Loaded/Failed events.
```cpp
UCASMobileAds::LoadMRecAd();
```
<Image width="236" alt="image" src="/assets/unreal/MREC-Ads-1.png" />

<Info>
The `Event Once` checkbox will fire the Loaded/Failed event only once. if `Autoload Ads` used, events can be triggered many times while the game world exists.
</Info>

### Autoload mode
If enabled, the ad will automatically load new content when the current ad is dismissed or completed. Additionally, it will automatically retry loading the ad if an error occurs during the loading process.  

```cpp
UCASMobileAds::SetAutoloadMRecAd(true);
```

<Image width="211" alt="Image" src="/assets/unreal/MREC-Ads-2.png" />

You should call `LoadMRecAd()` once to create Ad Instance.

By default, autoloading is defined in the `Project Settings -> Plugins -> CAS.AI Config -> Autoload MRec Ads`.

## Display the Ad
When you are ready to show the ad on the screen, just call the following method:
```cpp
UCASMobileAds::ShowMRecAd();
```
When you need to hide the ad from the user, just call the following method:
```cpp
UCASMobileAds::HideMRecAd();
```
<Image width="287" alt="image" src="/assets/unreal/MREC-Ads-3.png" />

<Info>
You can change the MRec's activity even if it is not ready to be shown yet. When the ad is ready, MRec will shown automatically.
</Info>

## Ad events
To further customize the behavior of your ad, you can hook into a number of events in the ad's lifecycle: loading, opening, closing, and so on. Listen for these events by registering a delegate for the appropriate event, as shown below.

```cpp
// Called when the ad loaded and ready to present.
UCASMobileAds::OnMRecAdLoaded.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("MRec loaded"));
});
// Сalled when an error occurred with the ad.
UCASMobileAds::OnMRecAdFailed.AddLambda([=](ECASError Error){
    UE_LOG(LogTemp, Log, TEXT("MRec failed to load: %s"),
        UCASMobileAds::GetAdsErrorMessage(Error));
});
// Called when the user clicks on the Ad.
UCASMobileAds::OnMRecAdClicked.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("MRec clicked"));
});
```
<Info>
Ad events in Blueprints are registered in the Load nodes. Each new Load Ad node cancels previous node events.
</Info>

## Ad position
The position where the MRec ad should be placed. The `ECASPosition` enum lists the valid ad position values.  
By default, the MRec ad is centered at the bottom.  
Changing the position of a MRec ad **does not destroy** the current MRec or load a new one.  

Change the MRec position on screen using the following method:
```cpp
UCASMobileAds::SetMRecAdPosition(ECASPosition::TopCenter);
```
<Image width="257" alt="image" src="/assets/unreal/MREC-Ads-4.png" />

## Ad Refresh rate
An ad unit’s automatic refresh rate (in seconds) determines how often a new ad request is generated for that ad unit.  
We recommended using refresh rate 30 seconds. However, you can choose any value you want. Or set 0 to disable automatic refresh ads.

Change the MRec automatic refresh rate using the following method:
```cpp
UCASMobileAds::SetMRecAdRefreshInterval(RefreshIntervalInSeconds);
```
<Image width="210" alt="image" src="/assets/unreal/MREC-Ads-5.png" />

<Info>
- Ad requests should not be made when the device screen is turned off.  
- The `setAutoloadMRecAd()` has no effect on refreshing the banner ad.
</Info>

## Release ad resource
Destroys the ad content and releases any associated resources when the ad is no longer needed to clean up resources and prevent memory leaks.

```cpp
UCASMobileAds::DestroyMRecAd();
```
<Image width="147" alt="image" src="/assets/unreal/MREC-Ads-6.png" />

Call `LoadMRecAd` to load new ad and restore autoload mode if used.

## Ad Availability
You can ask for the ad availability directly by calling the following function:
```cpp
bool MRecLoaded = UCASMobileAds::IsMRecAdReady();
```
<Image width="149" alt="image" src="/assets/unreal/MREC-Ads-7.png" />

<Warning>  
We don’t recommend waiting for `IsMRecAdReady` to change each frame. This property call the native SDK and can affect the performance of your game. Subscribe to the `OnMRecAdLoaded` event instead.
</Warning>
```

### Privacy Regulations

Source: https://production.docs.page/docs/unreal/privacy-regulations

```mdx

CleverAdsSolutions requires you to set flags indicating whether users are in an age-restricted category.

## Prohibition on Personal Information from Children
Publishers may designate all inventory within their applications as being child-directed or as COPPA-applicable though our UI. Publishers who have knowledge of specific individuals as being COPPA-applicable should make use of the API discussed below to inform CAS and all downstream consumers of this information.  

<Info>
Read more about [Children’s Online Privacy Protection Act (COPPA)](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children%27s-privacy)
</Info>

### Children Audience
If you know that the user falls within an age-restricted category (i.e., under the age of 16), you must set the `Children` audience flag:
```cpp
UCASMobileAds::SetUserAudienceForAds(ECASAudience::Children);
```
It also allows application to comply with the Google Play Families Policy requirements:
 - Ads displayed to those users do not involve interest-based advertising or remarketing;
 - Ads displayed to those users present content that is appropriate for children;
 - Ads displayed to those users follow the Families ad format requirements;
 - Compliance with all applicable legal regulations and industry standards relating to advertising to children.
 
### Not Children Audience
If you know that the user does not fall within an age-restricted category, you must set the `NotChildren` audience flag:
```cpp
UCASMobileAds::SetUserAudienceForAds(ECASAudience::NotChildren);
```
<Image width="296" alt="image" src="/assets/unreal/Privacy-Regulations-1.png" />

### Undefined Audience
The user's age has not been determined.
```cpp
UCASMobileAds::SetUserAudienceForAds(ECASAudience::Undefined);
```
If your app's target age groups include both children and older audiences, any ads that may be shown to children must comply with Google Play's Families Ads Program.  
A neutral age screen must be implemented so that any ads not suitable for children are only shown to older audiences.  
A neutral age screen is a mechanism to verify a user's age in a way that doesn't encourage them to falsify their age and gain access to areas of your app that aren't designed for children, for example, an age gate.
```

### Rewarded Ads

Source: https://production.docs.page/docs/unreal/rewarded-ads

```mdx

Rewarded ads let you offer users in-app items, such as continued gameplay, virtual currency, or other rewards, in exchange for their engagement with ads. 
Rewarded ads boost engagement because users receive a tangible benefit for their time.

Below is a diagram showing the ad lifecycle.
<Image zoom src="/assets/Lifecycle-Rewarded-Ad.png" alt="Diagram" height="500" />


## Load an Ad
Call manual load ad before each show if `Autoload Rewarded Ads` not checked.  
In Blueprints you can use Load node just for register Loaded/Failed events.
```cpp
UCASMobileAds::LoadRewardedAd();
```
<Image width="234" alt="image" src="/assets/unreal/Rewarded-Ads-1.png" />

<Info>
The `Event Once` checkbox will fire the Loaded/Failed event only once. if `Autoload Ads` used, events can be triggered many times while the game world exists.
</Info>

### Autoload mode
If enabled, the ad will automatically load new content when the current ad is dismissed or completed. Additionally, it will automatically retry loading the ad if an error occurs during the loading process.  

```cpp
UCASMobileAds::SetAutoloadRewardedAd(true);
```

<Image width="232" alt="Image" src="/assets/unreal/Rewarded-Ads-2.png" />

You should call `LoadRewardedAd()` once to create Ad Instance.

By default, autoloading is defined in the `Project Settings -> Plugins -> CAS.AI Config -> Autoload Rewarded Ads`.

## Ad events
To further customize the behavior of your ad, you can hook into a number of events in the ad's lifecycle: loading, opening, closing, and so on. Listen for these events by registering a delegate for the appropriate event, as shown below.

```cpp
// Called when user earned reward.
UCASMobileAds::OnRewardedAdEarnedReward.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("User Earned reward"));
});
// Called when ad ready to shown.
UCASMobileAds::OnRewardedAdLoaded.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("Rewarded loaded"));
});
// Called when ad failed to load with error.
UCASMobileAds::OnRewardedAdLoadFailed.AddLambda([=](ECASError Error){
    UE_LOG(LogTemp, Log, TEXT("Rewarded failed to load: %s"),
        UCASMobileAds::GetAdsErrorMessage(Error));
});
// Called when the ad shown.
UCASMobileAds::OnRewardedAdDisplayed.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("Rewarded displayed"));
});
// Called when the ad is failed to display.
UCASMobileAds::OnRewardedAdShowFailed.AddLambda([=](ECASError Error){
    UE_LOG(LogTemp, Log, TEXT("Rewarded failed to show: %s"),
        UCASMobileAds::GetAdsErrorMessage(Error));
});
// Called when the user clicks on the Ad.
UCASMobileAds::OnRewardedAdClicked.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("Rewarded clicked"));
});
// Called when the ad is closed.
UCASMobileAds::OnRewardedAdDismissed.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("Rewarded dismissed"));
});
```
<Info>
Ad events in Blueprints are registered in the Load and Show nodes. Each new Load/Show Ad node cancels previous node events.
</Info>

## Show the Ad
Before displaying a rewarded ad to users, you must present the user with an explicit choice to view rewarded ad content in exchange for a reward. Rewarded ads must always be an opt-in experience.

Subscribe to `OnRewardedAdEarnedReward` event to reward the user.

```cpp
UCASMobileAds::ShowRewardedAd();
```
<Image width="196" alt="image" src="/assets/unreal/Rewarded-Ads-3.png" />

## Release ad resource
Destroys the ad content and releases any associated resources when the ad is no longer needed to clean up resources and prevent memory leaks.

```cpp
UCASMobileAds::DestroyRewardedAd();
```
<Image width="201" alt="Image" src="/assets/unreal/Rewarded-Ads-4.png" />

Call `LoadRewardedAd` to load new ad and restore autoload mode if used.

## Ad Availability
You can ask for the ad availability directly by calling the following function:
```cpp
bool AdLoaded = UCASMobileAds::IsRewardedAdReady();
```
<Image width="175" alt="image" src="/assets/unreal/Rewarded-Ads-5.png" />

<Warning>  
We don’t recommend waiting for `IsRewardedAdReady` to change each frame. This method call the native SDK and can affect the performance of your game.  
Subscribe to the `OnRewardedAdLoaded` event instead.
</Warning>

## Muted Ads Sounds
Sounds in Rewarded and Rewarded ads mute state. Disabled by default.  
```cpp
UCASMobileAds::SetAdsMuted(Mute);
```
<Image width="134" alt="image" src="/assets/unreal/Rewarded-Ads-6.png" />
```

### Targeting options

Source: https://production.docs.page/docs/unreal/targeting-options

```mdx

You can now easily tailor the way you serve your ads to fit a specific audience!  
You’ll need to inform our servers of the users’ details so the SDK will know to serve ads according
to the segment the user belongs to.

## User Id
The userID is a unique identifier supplied by your application and must be static for each user across sessions. 
```cpp
UCASMobileAds::SetUserIDForAds(SomeStringWithID);
```

<Warning>  
Your userID should not contain any personally identifiable information such as  an email address, screen name, Android ID (AID), Apple Advertising ID (IDFA), or Google Advertising ID (GAID).
</Warning>

## User Age

Set user age. Limitation: 1-99 and 0 is 'unknown'.

```cpp
UCASMobileAds::SetUserAgeForAds(12);
```
<Image width="143" alt="image" src="/assets/unreal/Targeting-options-1.png" />

## User Gender

Set user gender.

```cpp
UCASMobileAds::SetUserGenderForAds(ECASGender::Male);
```
<Image width="218" alt="image" src="/assets/unreal/Targeting-options-2.png" />
```

### User Consent Flow

Source: https://production.docs.page/docs/unreal/user-consent-flow

```mdx

In order for CAS and our ad providers to deliver ads that are more relevant to your users, as a mobile app publisher, you need to collect explicit user consent.

<Info>
If you implement a CMP that is compliant with IAB TCF v2 ([Transparency & Consent Framework](https://iabeurope.eu/tcf-2-0/)) for your user consent flow, the CAS SDK supports sending the TCF v2 consent to networks. In this case, the CAS Consent Flow will not be shown to the user.
</Info>

<Warning>  
If you integrate your own CMP flow, make sure the flow completes before you initialize the CAS SDK.
</Warning>

### 1. Opt-in consent for the collection and use of personal data in the regions covered by GDPR, CCPA, LGPD, PIPEDA.
Any businesses established are required to comply with GDPR in Europe, CCPA in California, LGPD in Brazil, PIPEDA in Canada or risk facing heavy fines.

<Info>
Keep in mind that it’s best to contact qualified legal professionals, if you haven’t done so already, to get more information and be well-prepared for compliance.  

Read more about:
- GDPR - [General Data Protection Regulation](https://gdpr-info.eu)
- CCPA - [The California Consumer Privacy Act](https://theccpa.org)
- LGPD - [General Personal Data Protection Act](https://lgpd-brazil.info)
- PIPEDA - [The Personal Information Protection and Electronic Documents Act](https://www.priv.gc.ca/en/privacy-topics/privacy-laws-in-canada/the-personal-information-protection-and-electronic-documents-act-pipeda/)
</Info>

To provide users of your app with a consent dialog, review the possible solutions and select one for your app.
 - Standalone CAS [Automatic Consent Flow](unreal/user-consent-flow#automatic-consent-flow). This means you don't need to add anything else.
 - [Custom Consent Logic](unreal/user-consent-flow#custom-consent-logic) if you are using your own or a third-party party consent mechanism. 

### 2. Asking Apple's user permission to track them or access their device’s advertising identifier
With iOS 14.5 and later, you need to receive the user’s permission through the `AppTrackingTransparency` framework in order to track them or access their device’s advertising identifier. Read more about Asking Permission to Track and AppTrackingTransparency Framework on [Apple developer page](https://developer.apple.com/app-store/user-privacy-and-data-use/)

<Warning>  
If an iOS App does not present this request, the IDFA will automatically be zeroed out, which may lead to a significant loss in ad revenue.
</Warning>

## Overview flow
<Image height="400" alt="image" src="/assets/User-Consent-Flow-1.png" />

#### Users will not see the Consent dialog if at least one of following is true
- Users located in regions that are not covered by information protection
- Users who are subject to COPPA restrictions.
#### Users will not see the ATT request if at least one of the following is true
- Users using iOS versions below 14.5
- Users who have indicated that they do not allow apps to ask to track them, by setting *Settings > Privacy, Allow Apps to Request to Track*
- Users with child accounts, or who are under age 18, who are signed in via their Apple ID
- Users who have already answered so far
- The app does not have a usage tracking description in **Info.plist** under `NSUserTrackingUsageDescription` key

## Automatic consent flow
To get consent for collecting personal data of your users, we suggest you use a built-in Consent Flow, comes with a pre-made consent form that you can easily present to your users. That means you no longer need to create your own consent window.  

The user will see the consent flow when your app initialize ads. When the user completes the flow, the SDK fire `OnConsentFlowDismissed` event.
```cpp
UCASMobileAds::OnConsentFlowDismissed.AddLambda([=](){
    UE_LOG(LogTemp, Log, TEXT("User Consent Flow dismissed"));
});
```

The initialization completion event will also be called only after the consent dialog is dismissed, so you can simple use one event.
```cpp
UCASMobileAds::OnAdsInitialized.AddLambda([=](const FCASInitialConfig& Config){
    UE_LOG(LogTemp, Log, TEXT("User Consent Flow dismissed and Ads Initialized"));
});
```
<Image width="271" alt="image" src="/assets/unreal/User-Consent-Flow-2.png" />

CAS consent flow is enabled by default. You can disable the consent flow in `Edit > Project Settings > Plugins > CAS.AI Config - [Platform]` menu.

<Error>  
You must wait until the user finishes the consent flow before you initialize third-party SDKs (such as MMPs or analytics SDKs). For this reason, initialize such SDKs from within your initialization-completion callback. If you were to initialize these third-party SDKs before the user completes the consent flow, these third-party SDKs would not be able to access relevant identifiers and you would suffer a material impact on measurement, reporting, and ad revenue.
</Error>

## Manual consent flow
Call `ShowAdConsentFlowIfRequired()`. If the consent is required, the SDK loads a form and immediately presents it . 
The `OnConsentFlowResult` is called after the form is dismissed. If consent is not required, the `OnConsentFlowResult` is called immediately. The `FCASConsentFlowStatus` with which the form is dismissed will be passed to the event argument.
```cpp
void UHandlerClass::ShowConsentFlow() {
    UCASMobileAds::OnConsentFlowResult.AddUObject(this, &UHandlerClass::HandleResult);
    UCASMobileAds::ShowAdConsentFlowIfRequired();
}

void UHandlerClass::HandleResult(FCASConsentFlowStatus Status) {
    if(Status == FCASConsentFlowStatus::Obtained) {
        // User consent obtained.
    }
}
```
<Image width="204" alt="image" src="/assets/unreal/User-Consent-Flow-3.png" />

- **OnCompleted**  
The delegate will be invoked when the Consent Flow is dismissed with one of the statuses: `Obtained`, `NotRequired`, `Unavailable`.
- **OnFailed**  
The delegate event will be invoked when the Consent Flow is failed with error.

| ECASConsentFlowStatus | Description                                                        |
| --------------------- | ------------------------------------------------------------------ |
| Undefined             | Not used                                                           |
| Obtained              | User consent obtained. Personalized vs non-personalized undefined. |
| NotRequired           | User consent not required.                                         |
| Unavailable           | User consent unavailable.                                          |
| InternalError         | There was an internal error.                                       |
| NetworkError          | There was an error loading data from the network                   |
| NotForegroundApp      | There was the app not foreground error.                            |
| FlowStillPresenting   | There was an error with another form is still being displayed      |

<Warning>  
The cache consent status on your app or a previously saved consent string, could lead to a [TCF 3.3](https://support.google.com/admanager/answer/9999955) error if consent is expired.
</Warning>

## Privacy options button
Some consent forms require the user to modify their consent at any time. Adhere to the following steps to implement a privacy options button if required.
1. Implement a UI element, such as a button in your app's settings page, that can trigger a privacy options form.
2. Once `ShowAdConsentFlowIfRequired()` completes, check `IsUserAdConsentRequired` to determine whether to display the UI element that can present the privacy options form.
3. When a user interacts with your UI element, call `ShowAdConsentFlow()` to show the form so the user can update their privacy options at any time.

```cpp
void UConsentHandlerClass::InitPrivacyOptionsButton() {
    if (UCASMobileAds::IsUserAdConsentRequired()) {
        // Add button to UI
    }
}
```
<Image width="179" alt="image" src="/assets/unreal/User-Consent-Flow-4.png" />

```cpp
void UConsentHandlerClass::ShowPrivacyOptionsForm() {
    UCASMobileAds::OnConsentFlowResult.AddUObject(this, &UHandlerClass::HandleResult);
    UCASMobileAds::ShowAdConsentFlow();
}
```
<Image width="202" alt="image" src="/assets/unreal/User-Consent-Flow-5.png" />

## Debug geography
The SDK provides a way to test your app's behavior as though the device was located in the EEA or UK using the `Edit > Project Settings > Plugins > CAS.AI Config - [Platform]` menu and `User Debug Geography` property.

<Image width="401" alt="image" src="/assets/unreal/User-Consent-Flow-6.png" />

<Info>
Note that debug geography only work if in CAS Settings window:
- Active test device defined.
- Active Test Ads Mode
</Info>

## Meta Audience Network Data Processing Options for Users in California
The CAS does not support your handling of CCPA opt-out values for Meta Audience Network, you must work directly with the network to  purposes of your obligations for CCPA compliance.  

To learn how to implement Meta Audience Network’s “Limited Data Use” flag, read the [Additional Meta AudienceNetwork steps](unreal/additional-meta-audiencenetwork-steps).

# Custom Consent Logic
The following instructions apply if you are using your own or a third-party party consent mechanism. 

<Error>  
If you access Google demand through CAS, it’s critical that you review the [Google CMP requirements](https://support.google.com/adsense/answer/13554116) before you start the integration process.
</Error>

<Warning>  
You must set the privacy options before creating the CAS Manager to disable the automatic CAS consent flow and advertising SDKs are initialized respecting the user's consent.
</Warning>

### Consent in GDPR and Other regions
CAS shares these set consent values via adapters to supported mediation partners.  

If the user consents to interest-based advertising, set the user consent `Accepted` flag:
```cpp
UCASMobileAds::SetUserConsentForAds(ECASUserConsentStatus::Accepted);
```
<Image width="220" alt="image" src="/assets/unreal/User-Consent-Flow-7.png" />

If the user does NOT consent to interest-based advertising, set the user consent `Denied` flag:
```cpp
UCASMobileAds::SetUserConsentForAds(ECASUserConsentStatus::Denied);
```

Once you set the consent value, CAS will continue to respect that value for the lifetime of your application or until the user consents to interest-based advertising.

### Multi-State Consumer privacy laws
California and Virginia laws may require you to display a “Do Not Sell or Share My Personal Information” link or provide other options to users located in those states to opt out of interest-based advertising. You must set a flag that indicates whether users in those states opt out of interest-based advertising or the sale or share of personal information for interest-based advertising.

If a user does NOT opt out of interest-based advertising, set the `OptInSale` flag: 
```cpp
UCASMobileAds::SetUserOptOutSaleForAds(ECASUserCCPAStatus::OptInSale);
```
<Image width="221" alt="image" src="/assets/unreal/User-Consent-Flow-8.png" />

If a user does opt out of interest-based advertising, set the `OptOutSale` flag:
```cpp
UCASMobileAds::SetUserOptOutSaleForAds(ECASUserCCPAStatus::OptOutSale);
```
You do not need to set this flag for users who are outside California. If you do set this flag for such users, this will not impact how ads are served to them.
```

### Verify Integration

Source: https://production.docs.page/docs/unreal/verify-integration

```mdx

The CAS SDK provides an easy way to verify that you’ve successfully integrated any additional adapters; it also makes sure all required dependencies and frameworks were added for the various mediated ad networks.   
After you have finished your integration, call the following static method and confirm that all networks you have implemented are marked as VERIFIED:  
```cpp
UCASMobileAds::ValidateAdsIntegration();
```

<Image width="185" alt="image" src="/assets/unreal/Verify-Integration-1.png" />

Find log information by tag: **CASIntegrationHelper**

Once you’ve successfully verified your integration, please remember to **remove the integration helper from your code**.

The Integration Helper tool reviews everything, including ad networks you may have intentionally chosen NOT to include in your application. These will appear as MISSING and there is no reason for concern. In the case the ad network’s integration has not been completed successfully, it will be marked as NOT VERIFIED.

## Verbose Debug logging
The enabled Debug Mode will display a lot of useful information for debugging about the states of the SDK with tag `CAS.AI`.  
Disabled by default. Disabling Debug Mode may improve application performance.  
You can enable logging change the flag at any time using the following method:
```cpp
UCASMobileAds::SetVerboseAdsLogs(Enabled);
```

<Image width="174" alt="image" src="/assets/unreal/Verify-Integration-2.png" />

<Info>
If you have discovered the problem in the work of the SDK, please provide us with a description of the problem along with the full log of your device.
</Info>

## Don’t forget to implement app-ads.txt
For both iOS and Android integrations, we encourage our partners to adopt this file and help us combat ad fraud.  
Read detailed instructions on [how to create and upload your app-ads.txt file](/general/authorized-sellers-for-apps).
```
