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

# Native Ads

Native ads deliver individual ad assets (headline, body text, icon, media, and call-to-action) that you render inside your own layout, so ads blend naturally with your app's content. Unlike banner or interstitial formats, native ads give you full design control: you choose the layout, fonts, colors, and placement. DT FairBid mediates demand from multiple networks through a single, unified API; your layout code never needs to know which network served the ad.

{% hint style="warning" %}
Before integrating native ads, ensure that you are aware of the following requirements and limitations:

* Native ads require FairBid SDK 3.68.0 or later.
* Not all networks support this format. For more information about which networks support native ads, see [Supported Networks](/dt-fairbid/fairbid-sdk/supported-networks.md).
* There is no Unity support for native ads.
  {% endhint %}

## Integrating Native Ads

Native ads can be integrated into your app in the following ways:

* **Single ad slot**: a dedicated placement, for example between content or at the bottom of a screen. The slot creates one view that holds the same ad for the life of the screen.
* **Scrollable list**: a list of rows, for example a news feed, that recycles a small, fixed pool of views as the user scrolls instead of creating a new view for every item. Because views are reused, a row shows different ads over time instead of holding one ad for the life of the screen.

Either integration follows the same process, but the timing of some steps differs.

{% stepper %}
{% step %}

#### [Request a Native Ad](#request-a-native-ad)

Pass a listener (a delegate on iOS) to the request call to receive the loaded ad or a failure.
{% endstep %}

{% step %}

#### [Build and Wire the Layout](#build-and-wire-the-layout)

Create a `NativeAdView` (Android) or `FYBNativeAdView` (iOS) and assign your sub-views for each asset slot.
{% endstep %}

{% step %}

#### [Bind the Ad to the View](#bind-the-ad-to-the-view)

Call `setNativeAd` to populate the layout and register tracking.
{% endstep %}

{% step %}

#### [Handle Events](#handle-events)

Assign a listener (a delegate on iOS) to the loaded ad to receive impression, click, and error callbacks.
{% endstep %}

{% step %}

#### [Destroy the Ad](#destroy-the-ad)

Release resources when the ad is no longer needed.
{% endstep %}
{% endstepper %}

### Request a Native Ad <a href="#request-a-native-ad" id="request-a-native-ad"></a>

Pass a listener (a delegate on iOS) to the request call. The listener or delegate is scoped to a single request and receives exactly one terminal callback: either a successful load or a failure.

{% hint style="warning" %}
A request owns its placement until the load or failure callback (`onLoad` / `onFailedToLoad` on Android, `nativeAdDidLoad` / `nativeAdDidFailToLoad` on iOS) fires. To reload a placement, wait for that callback before requesting it again.
{% endhint %}

#### For a Single Ad Slot

{% tabs %}
{% tab title="Android" %}
{% code title="Kotlin" %}

```kotlin
Native.request("YOUR_PLACEMENT_ID", object : NativeAdLoadListener {
    override fun onLoad(placementId: String, nativeAd: NativeAd) {
        // Ad is ready. Bind it to your view.
    }

    override fun onFailedToLoad(placementId: String, error: NativeAdError) {
        // No fill. Retry with exponential backoff (see Retry with Exponential Backoff).
    }

    override fun onRequestStart(placementId: String, requestId: String) {
        // Called when the request is sent to the ad server. Use requestId for debugging.
    }
})
```

{% endcode %}

{% code title="Java" %}

```java
Native.request("YOUR_PLACEMENT_ID", new NativeAdLoadListener() {
    @Override
    public void onLoad(String placementId, NativeAd nativeAd) {
        // Ad is ready. Bind it to your view.
    }

    @Override
    public void onFailedToLoad(String placementId, NativeAdError error) {
        // No fill. Retry with exponential backoff (see Retry with Exponential Backoff).
    }

    @Override
    public void onRequestStart(String placementId, String requestId) {
        // Called when the request is sent to the ad server.
    }
});
```

{% endcode %}
{% endtab %}

{% tab title="iOS" %}
{% code title="Swift" %}

```swift
extension MyViewController: FYBNativeAdLoadDelegate {

    func requestNativeAd() {
        FYBNative.request("YOUR_PLACEMENT_ID", delegate: self)
    }

    func nativeAdDidLoad(_ placementId: String, nativeAd: FYBNativeAd) {
        // Ad is ready. Bind it to your view.
    }

    func nativeAdDidFailToLoad(_ placementId: String, withError error: Error) {
        // No fill. Retry with exponential backoff (see Retry with Exponential Backoff).
    }

    func nativeAdDidRequestStart(_ placementId: String, requestId: String) {
        // Called when the request is sent to the ad server.
    }
}
```

{% endcode %}

{% code title="Objective-C" %}

```objectivec
- (void)requestNativeAd {
    [FYBNative requestWithPlacementId:@"YOUR_PLACEMENT_ID" delegate:self];
}

#pragma mark - FYBNativeAdLoadDelegate

- (void)nativeAdDidLoad:(NSString *)placementId nativeAd:(FYBNativeAd *)nativeAd {
    // Ad is ready. Bind it to your view.
}

- (void)nativeAdDidFailToLoad:(NSString *)placementId withError:(NSError *)error {
    // No fill. Retry with exponential backoff (see Retry with Exponential Backoff).
}

- (void)nativeAdDidRequestStart:(NSString *)placementId requestId:(NSString *)requestId {
    // Called when the request is sent to the ad server.
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

#### For a Scrollable List

For a scrollable list, a small, fixed number of row views is reused as the user scrolls, instead of creating a new view for each ad as a single ad slot does. A row that currently holds an ad can later be recycled to show a different ad or different content.

Request an ad for each placement when the screen opens, and hold the loaded ad until a row is bound. Once an ad is shown, the next request is chained from the `onShow` / `nativeAdDidShow` callback of whichever ad was just bound. In this way, the placement always has a fresh ad ready before it's needed. An ad that is loaded but never shown counts as a fill without an impression. For more information on the full request-bind-request cycle, see [Bind the Ad to the View](#bind-the-ad-to-the-view).

{% hint style="warning" %}
Do not request an ad from `onBindViewHolder()` (Android) or `cellForRowAt` (iOS). These callbacks fire when a row becomes visible, which can trigger duplicate or wasted requests as rows are recycled.
{% endhint %}

#### Retry with Exponential Backoff <a href="#retry-with-exponential-backoff" id="retry-with-exponential-backoff"></a>

When a request fails with no fill, do not retry immediately. Retry with exponential backoff instead, doubling the delay after each consecutive failure, for example 2, 4, 8, 16, and 32 seconds. Reset the delay after a successful load.

### Build and Wire the Layout <a href="#build-and-wire-the-layout" id="build-and-wire-the-layout"></a>

Create a `NativeAdView` (Android) or `FYBNativeAdView` (iOS) and assign your sub-views for each asset slot you plan to display (unused slots can be omitted).

{% tabs %}
{% tab title="Android" %}
Define your layout in XML. Adapt the following example XML to your app's visual design.

{% code title="XML" %}

```xml
<!-- res/layout/native_ad_item.xml -->
<com.fyber.fairbid.ads.nativead.NativeAdView
    android:id="@+id/native_ad_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="8dp">

        <!-- Icon + headline row -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <ImageView
                android:id="@+id/native_ad_icon"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:scaleType="centerCrop"/>
            <TextView
                android:id="@+id/native_ad_title"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textStyle="bold"/>
        </LinearLayout>

        <!-- Media -->
        <FrameLayout
            android:id="@+id/native_ad_media"
            android:layout_width="match_parent"
            android:layout_height="200dp"/>

        <!-- Body + CTA -->
        <TextView
            android:id="@+id/native_ad_body"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/native_ad_cta"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <!-- AdChoices (required by policy) -->
        <FrameLayout
            android:id="@+id/native_ad_choices"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_gravity="end"/>
    </LinearLayout>
</com.fyber.fairbid.ads.nativead.NativeAdView>
```

{% endcode %}

Wire the asset views in code:

{% code title="Kotlin" %}

```kotlin
private fun setupNativeAdView(root: View): NativeAdView {
    val adView = root.findViewById<NativeAdView>(R.id.native_ad_view)
    adView.titleView        = root.findViewById(R.id.native_ad_title)
    adView.bodyView         = root.findViewById(R.id.native_ad_body)
    adView.callToActionView = root.findViewById(R.id.native_ad_cta)
    adView.iconView         = root.findViewById(R.id.native_ad_icon)
    adView.mediaView        = root.findViewById(R.id.native_ad_media)
    adView.adChoicesView    = root.findViewById(R.id.native_ad_choices)
    return adView
}
```

{% endcode %}

{% code title="Java" %}

```java
private NativeAdView setupNativeAdView(View root) {
    NativeAdView adView = root.findViewById(R.id.native_ad_view);
    adView.setTitleView(root.findViewById(R.id.native_ad_title));
    adView.setBodyView(root.findViewById(R.id.native_ad_body));
    adView.setCallToActionView(root.findViewById(R.id.native_ad_cta));
    adView.setIconView(root.findViewById(R.id.native_ad_icon));
    adView.setMediaView(root.findViewById(R.id.native_ad_media));
    adView.setAdChoicesView(root.findViewById(R.id.native_ad_choices));
    return adView;
}
```

{% endcode %}
{% endtab %}

{% tab title="iOS" %}
Design your `FYBNativeAdView` layout in a `.xib` file, connect its outlets in Interface Builder, and then instantiate it from the nib at runtime:

{% code title="Swift" %}

```swift
let nib = UINib(nibName: "MyNativeView", bundle: .main)
let adView = nib.instantiate(withOwner: nil, options: nil).first as! FYBNativeAdView
```

{% endcode %}

{% code title="Objective-C" %}

```objectivec
UINib *nib = [UINib nibWithNibName:@"MyNativeView" bundle:[NSBundle mainBundle]];
FYBNativeAdView *adView = (FYBNativeAdView *)[[nib instantiateWithOwner:nil options:nil] firstObject];
```

{% endcode %}

<div align="left" data-with-frame="true"><img src="https://2654615282-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4IftQ9WUOy9feTA5sZeE%2Fuploads%2Fgit-blob-b00346468103243433088a99d4350fe016f4859b%2Ffybnativeadview-ib-outlets.png?alt=media" alt="FYBNativeAdView outlets connected in Interface Builder"></div>

{% hint style="warning" %}
Interface Builder cannot discover outlets from a class inside an `.xcframework`. This is an Apple bug with no known fix date. When `FairBidSDK.xcframework` is your only source of `FYBNativeAdView`, the outlets panel in Xcode stays empty and connections cannot be made.

As a workaround, copy `FYBNativeAdView.h` into your project so the header is compiled into your target. Once Xcode sees the header, all `IBOutlet` properties appear in Interface Builder and can be connected normally. Keep the copy in sync with the header shipped in the SDK.
{% endhint %}
{% endtab %}
{% endtabs %}

#### For a Scrollable List

Either assign the ad row a fixed height, or let the row wrap content and size the media view from `mediaAspectRatio` at bind time. For more information, see [Bind the Ad to the View](#bind-the-ad-to-the-view). Avoid resizing the view once it is displayed on screen.

When collapsing unfilled ad slots, change the row's height in one step to avoid jitter.

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

* Set `itemView.visibility = View.GONE`.
* Do not also reassign `itemView.layoutParams = RecyclerView.LayoutParams(0, 0)`. The extra measurement pass causes `ItemAnimator` to glitch and snap during fast flings.
  {% endtab %}

{% tab title="iOS" %}

* For an empty ad row, return `0` from `tableView(_:heightForRowAt:)`.
* When a fill arrives, call `tableView.beginUpdates()` and `tableView.endUpdates()` around the height change to animate it. Using `reloadRows(at:with:)` reconfigures the cell and can re-bind the ad.
  {% endtab %}
  {% endtabs %}

### Bind the Ad to the View <a href="#bind-the-ad-to-the-view" id="bind-the-ad-to-the-view"></a>

Call `setNativeAd` after wiring the layout slots. The SDK populates text fields, loads the icon and media into their containers, and registers all views with the underlying network SDK for impression and click tracking.

When a network reports the media asset's width/height ratio, `nativeAd.mediaAspectRatio` provides the value. Not all networks report this ratio. When the ratio is present and greater than zero, apply it as a layout constraint before the layout pass so the container is sized correctly for both image and video fills. When the ratio is absent or zero, let the media view size itself to fit its content.

#### For a Single Ad Slot

{% tabs %}
{% tab title="Android" %}
{% code title="Kotlin" %}

```kotlin
fun renderNativeAd(nativeAd: NativeAd) {
    val adView = setupNativeAdView(
        layoutInflater.inflate(R.layout.native_ad_item, binding.adContainer, false)
    )
    nativeAd.mediaAspectRatio?.takeIf { it > 0 }?.let { ratio ->
        adView.mediaView?.let { mediaView ->
            mediaView.post {
                val w = mediaView.width
                if (w > 0) {
                    mediaView.updateLayoutParams { height = (w / ratio).toInt() }
                }
            }
        }
    }
    adView.setNativeAd(nativeAd)
    binding.adContainer.addView(adView)
}
```

{% endcode %}

{% code title="Java" %}

```java
private void renderNativeAd(NativeAd nativeAd) {
    NativeAdView adView = setupNativeAdView(
        getLayoutInflater().inflate(R.layout.native_ad_item, binding.adContainer, false));
    Float ratio = nativeAd.getMediaAspectRatio();
    if (ratio != null && ratio > 0) {
        View mediaView = adView.getMediaView();
        if (mediaView != null) {
            float r = ratio;
            mediaView.post(() -> {
                int w = mediaView.getWidth();
                if (w > 0) {
                    ViewGroup.LayoutParams lp = mediaView.getLayoutParams();
                    lp.height = (int) (w / r);
                    mediaView.setLayoutParams(lp);
                }
            });
        }
    }
    adView.setNativeAd(nativeAd);
    binding.adContainer.addView(adView);
}
```

{% endcode %}
{% endtab %}

{% tab title="iOS" %}
{% code title="Swift" %}

```swift
func renderNativeAd(_ nativeAd: FYBNativeAd) {
    let nib = UINib(nibName: "MyNativeView", bundle: .main)
    let adView = nib.instantiate(withOwner: nil, options: nil).first as! FYBNativeAdView

    if let ratio = nativeAd.mediaAspectRatio?.floatValue, ratio > 0,
       let mediaView = adView.mediaView {
        mediaView.widthAnchor.constraint(
            equalTo: mediaView.heightAnchor,
            multiplier: CGFloat(ratio)
        ).isActive = true
    }

    adView.setNativeAd(nativeAd)
    containerView.addSubview(adView)
}
```

{% endcode %}

{% code title="Objective-C" %}

```objectivec
- (void)renderNativeAd:(FYBNativeAd *)nativeAd {
    UINib *nib = [UINib nibWithNibName:@"MyNativeView" bundle:[NSBundle mainBundle]];
    FYBNativeAdView *adView = (FYBNativeAdView *)[[nib instantiateWithOwner:nil options:nil] firstObject];

    NSNumber *ratio = nativeAd.mediaAspectRatio;
    if (ratio != nil && ratio.floatValue > 0 && adView.mediaView != nil) {
        [[adView.mediaView.widthAnchor constraintEqualToAnchor:adView.mediaView.heightAnchor
                                                   multiplier:ratio.floatValue] setActive:YES];
    }

    [adView setNativeAd:nativeAd];
    [self.containerView addSubview:adView];
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

#### For a Scrollable List

Row layouts in a scrollable list typically host the ad inside a dedicated container subview (`adContainer`: a `FrameLayout` on Android, a `UIView` on iOS) alongside surrounding UI such as a "Sponsored" label.

When the screen opens, request the ad for each placement and hold it in a map (`readyAds`) until it's needed for binding. Then, in one step, take it from that map (`takeAdView()`), attach its listener (`adListener`), and bind it to a fresh view (`setNativeAd()`). Attaching the listener before binding ensures that no events are missed. Removing the ad from `readyAds` as part of the same call means the same `NativeAd` / `FYBNativeAd` instance can never be handed to a second row.

{% hint style="warning" %}

* Bind each ad instance to only one row. Reusing an instance across rows causes view hierarchy collisions, layout detachment bugs, and duplicate impression reporting.
* Re-binding a previously destroyed view causes clicks and impressions to stop registering.
  {% endhint %}

{% tabs %}
{% tab title="Android" %}
{% code title="Kotlin" %}

```kotlin
// In your Fragment or feed controller:
private val readyAds = mutableMapOf<String, NativeAd>()  // One loaded ad per placement

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    requestAd("YOUR_PLACEMENT_ID")  // Prime the placement when the screen opens
}

private fun requestAd(placementId: String) {
    Native.request(placementId, object : NativeAdLoadListener {
        override fun onLoad(placementId: String, nativeAd: NativeAd) {
            readyAds[placementId] = nativeAd
        }

        override fun onFailedToLoad(placementId: String, error: NativeAdError) {
            // No fill. Retry with exponential backoff, not from a scroll event.
        }

        override fun onRequestStart(placementId: String, requestId: String) {}
    })
}

// Called from onBindViewHolder: binds the ready ad to a fresh view, or returns null
fun takeAdView(placementId: String): NativeAdView? {
    val nativeAd = readyAds.remove(placementId) ?: return null
    nativeAd.adListener = object : NativeAdListener {
        override fun onShow(placementId: String, impressionData: ImpressionData) {
            requestAd(placementId)  // Request the next ad only after this one is seen
        }

        override fun onClick(placementId: String) {}

        override fun onError(placementId: String, error: NativeAdError) {}
    }
    // Helper that inflates native_ad_item.xml and wires asset views (see "Build and Wire the Layout")
    val adView = makeAdView()
    adView.setNativeAd(nativeAd)
    return adView
}

// In your RecyclerView.ViewHolder:
class NativeAdViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val adContainer: FrameLayout = itemView.findViewById(R.id.feed_ad_container)
    var adView: NativeAdView? = null
        private set

    fun attachAdView(adView: NativeAdView) {
        this.adView = adView
        adContainer.addView(adView)
    }

    fun destroyAdView() {
        adContainer.removeAllViews()
        adView?.destroy()  // Also destroys the bound NativeAd
        adView = null
    }
}

// In your RecyclerView.Adapter (feed is the Fragment or feed controller shown above):
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    if (holder is NativeAdViewHolder && holder.adView == null) {
        // No ready ad: leave the row empty or collapsed. Do not request here.
        val adView = feed.takeAdView("YOUR_PLACEMENT_ID") ?: return
        holder.attachAdView(adView)
    }
}
```

{% endcode %}

{% code title="Java" %}

```java
// In your Fragment or feed controller:
private final Map<String, NativeAd> readyAds = new HashMap<>(); // One loaded ad per placement

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    requestAd("YOUR_PLACEMENT_ID"); // Prime the placement when the screen opens
}

private void requestAd(String placementId) {
    Native.request(placementId, new NativeAdLoadListener() {
        @Override
        public void onLoad(String placementId, NativeAd nativeAd) {
            readyAds.put(placementId, nativeAd);
        }

        @Override
        public void onFailedToLoad(String placementId, NativeAdError error) {
            // No fill. Retry with exponential backoff, not from a scroll event.
        }

        @Override
        public void onRequestStart(String placementId, String requestId) {}
    });
}

// Called from onBindViewHolder: binds the ready ad to a fresh view, or returns null
@Nullable
NativeAdView takeAdView(String placementId) {
    NativeAd nativeAd = readyAds.remove(placementId);
    if (nativeAd == null) {
        return null;
    }
    nativeAd.setAdListener(new NativeAdListener() {
        @Override
        public void onShow(String placementId, ImpressionData impressionData) {
            requestAd(placementId); // Request the next ad only after this one is seen
        }

        @Override
        public void onClick(String placementId) {}

        @Override
        public void onError(String placementId, NativeAdError error) {}
    });
    // Helper that inflates native_ad_item.xml and wires asset views (see "Build and Wire the Layout")
    NativeAdView adView = makeAdView();
    adView.setNativeAd(nativeAd);
    return adView;
}

// In your RecyclerView.ViewHolder:
public class NativeAdViewHolder extends RecyclerView.ViewHolder {
    final FrameLayout adContainer;
    @Nullable NativeAdView adView;

    NativeAdViewHolder(View itemView) {
        super(itemView);
        adContainer = itemView.findViewById(R.id.feed_ad_container);
    }

    void attachAdView(NativeAdView adView) {
        this.adView = adView;
        adContainer.addView(adView);
    }

    void destroyAdView() {
        adContainer.removeAllViews();
        if (adView != null) {
            adView.destroy(); // Also destroys the bound NativeAd
            adView = null;
        }
    }
}

// In your RecyclerView.Adapter (feed is the Fragment or feed controller shown above):
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
    if (holder instanceof NativeAdViewHolder && ((NativeAdViewHolder) holder).adView == null) {
        // No ready ad: leave the row empty or collapsed. Do not request here.
        NativeAdView adView = feed.takeAdView("YOUR_PLACEMENT_ID");
        if (adView != null) {
            ((NativeAdViewHolder) holder).attachAdView(adView);
        }
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="iOS" %}
Load and show callbacks can arrive off the main thread, so the example switches to the main thread before it touches `readyAds` or sends the next request.

{% code title="Swift" %}

```swift
// In your view controller (FYBNativeAdLoadDelegate and FYBNativeAdDelegate):
private var readyAds: [String: FYBNativeAd] = [:]  // One loaded ad per placement

override func viewDidLoad() {
    super.viewDidLoad()
    FYBNative.request("YOUR_PLACEMENT_ID", delegate: self)  // Prime the placement when the screen opens
}

func nativeAdDidLoad(_ placementId: String, nativeAd: FYBNativeAd) {
    DispatchQueue.main.async { self.readyAds[placementId] = nativeAd }
}

func nativeAdDidFailToLoad(_ placementId: String, withError error: Error) {
    // No fill. Retry with exponential backoff, not from a scroll event.
}

// Called from cellForRowAt: binds the ready ad to a fresh view, or returns nil
func takeAdView(placementId: String) -> FYBNativeAdView? {
    guard let nativeAd = readyAds.removeValue(forKey: placementId) else { return nil }
    nativeAd.delegate = self
    // Helper that instantiates MyNativeView from nib and wires asset views (see "Build and Wire the Layout")
    let adView = makeAdView()
    adView.setNativeAd(nativeAd)
    return adView
}

func nativeAdDidShow(_ placementId: String, impressionData: FYBImpressionData) {
    // Request the next ad only after this one is seen
    DispatchQueue.main.async { FYBNative.request(placementId, delegate: self) }
}

// In your UITableViewCell subclass:
class NativeAdCell: UITableViewCell {
    @IBOutlet weak var adContainer: UIView!
    private(set) var adView: FYBNativeAdView?

    func attachAdView(_ adView: FYBNativeAdView) {
        self.adView = adView
        adContainer.addSubview(adView)
        adView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            adView.leadingAnchor.constraint(equalTo: adContainer.leadingAnchor),
            adView.trailingAnchor.constraint(equalTo: adContainer.trailingAnchor),
            adView.topAnchor.constraint(equalTo: adContainer.topAnchor),
            adView.bottomAnchor.constraint(equalTo: adContainer.bottomAnchor)
        ])
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        adView?.removeFromSuperview()
        adView?.destroy()
        adView = nil
    }
}

// In your UITableViewDataSource:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "NativeAdCell", for: indexPath) as! NativeAdCell
    // No ready ad: leave the row empty or collapsed. Do not request here.
    if cell.adView == nil, let adView = takeAdView(placementId: "YOUR_PLACEMENT_ID") {
        cell.attachAdView(adView)
    }
    return cell
}
```

{% endcode %}

{% code title="Objective-C" %}

```objectivec
// In your view controller:
@interface MyFeedViewController () <FYBNativeAdLoadDelegate, FYBNativeAdDelegate>
@property (nonatomic) NSMutableDictionary<NSString *, FYBNativeAd *> *readyAds; // One loaded ad per placement
@end

@implementation MyFeedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.readyAds = [NSMutableDictionary dictionary];
    [FYBNative requestWithPlacementId:@"YOUR_PLACEMENT_ID" delegate:self]; // Prime the placement when the screen opens
}

- (void)nativeAdDidLoad:(NSString *)placementId nativeAd:(FYBNativeAd *)nativeAd {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.readyAds[placementId] = nativeAd;
    });
}

- (void)nativeAdDidFailToLoad:(NSString *)placementId withError:(NSError *)error {
    // No fill. Retry with exponential backoff, not from a scroll event.
}

// Called from cellForRowAt: binds the ready ad to a fresh view, or returns nil
- (nullable FYBNativeAdView *)takeAdViewForPlacement:(NSString *)placementId {
    FYBNativeAd *nativeAd = self.readyAds[placementId];
    if (nativeAd == nil) {
        return nil;
    }
    [self.readyAds removeObjectForKey:placementId];
    nativeAd.delegate = self;
    // Helper that instantiates MyNativeView from nib and wires asset views (see "Build and Wire the Layout")
    FYBNativeAdView *adView = [self makeAdView];
    [adView setNativeAd:nativeAd];
    return adView;
}

- (void)nativeAdDidShow:(NSString *)placementId impressionData:(FYBImpressionData *)impressionData {
    // Request the next ad only after this one is seen
    dispatch_async(dispatch_get_main_queue(), ^{
        [FYBNative requestWithPlacementId:placementId delegate:self];
    });
}

@end

// In your UITableViewCell subclass:
@interface NativeAdCell : UITableViewCell
@property (nonatomic, weak) IBOutlet UIView *adContainer;
@property (nonatomic, strong, readonly, nullable) FYBNativeAdView *adView;
- (void)attachAdView:(FYBNativeAdView *)adView;
@end

@interface NativeAdCell ()
@property (nonatomic, strong, readwrite, nullable) FYBNativeAdView *adView;
@end

@implementation NativeAdCell

- (void)attachAdView:(FYBNativeAdView *)adView {
    self.adView = adView;
    [self.adContainer addSubview:adView];
    adView.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:@[
        [adView.leadingAnchor constraintEqualToAnchor:self.adContainer.leadingAnchor],
        [adView.trailingAnchor constraintEqualToAnchor:self.adContainer.trailingAnchor],
        [adView.topAnchor constraintEqualToAnchor:self.adContainer.topAnchor],
        [adView.bottomAnchor constraintEqualToAnchor:self.adContainer.bottomAnchor]
    ]];
}

- (void)prepareForReuse {
    [super prepareForReuse];
    [self.adView removeFromSuperview];
    [self.adView destroy];
    self.adView = nil;
}

@end

// In your UITableViewDataSource:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NativeAdCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NativeAdCell" forIndexPath:indexPath];
    // No ready ad: leave the row empty or collapsed. Do not request here.
    if (cell.adView == nil) {
        FYBNativeAdView *adView = [self takeAdViewForPlacement:@"YOUR_PLACEMENT_ID"];
        if (adView != nil) {
            [cell attachAdView:adView];
        }
    }
    return cell;
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

`destroyAdView()` (Android) / `prepareForReuse()` (iOS) above runs when a row is recycled, not shown here. For more information, see [Destroy the Ad](#destroy-the-ad).

### Handle Events <a href="#handle-events" id="handle-events"></a>

Assign a listener (a delegate on iOS) to the loaded ad to receive impression, click, and error callbacks. Set the listener or delegate inside `onLoad` / `nativeAdDidLoad`, ideally before calling `setNativeAd` so no events are missed during view binding.

#### For a Single Ad Slot

{% tabs %}
{% tab title="Android" %}
{% code title="Kotlin" %}

```kotlin
override fun onLoad(placementId: String, nativeAd: NativeAd) {
    nativeAd.adListener = object : NativeAdListener {
        override fun onShow(placementId: String, impressionData: ImpressionData) {
            // Called when the ad impression is recorded.
        }
        override fun onClick(placementId: String) {
            // Called when the user taps the ad.
        }
        override fun onError(placementId: String, error: NativeAdError) {
            // Called when a runtime error occurs after the ad is loaded.
        }
    }
    renderNativeAd(nativeAd)
}
```

{% endcode %}

{% code title="Java" %}

```java
@Override
public void onLoad(String placementId, NativeAd nativeAd) {
    nativeAd.setAdListener(new NativeAdListener() {
        @Override
        public void onShow(String placementId, ImpressionData impressionData) {
            // Called when the ad impression is recorded.
        }
        @Override
        public void onClick(String placementId) {
            // Called when the user taps the ad.
        }
        @Override
        public void onError(String placementId, NativeAdError error) {
            // Called when a runtime error occurs after the ad is loaded.
        }
    });
    renderNativeAd(nativeAd);
}
```

{% endcode %}
{% endtab %}

{% tab title="iOS" %}
{% code title="Swift" %}

```swift
func nativeAdDidLoad(_ placementId: String, nativeAd: FYBNativeAd) {
    nativeAd.delegate = self
    renderNativeAd(nativeAd)
}

// MARK: - FYBNativeAdDelegate

func nativeAdDidShow(_ placementId: String, impressionData: FYBImpressionData) {
    // Called when the ad impression is recorded.
}

func nativeAdDidClick(_ placementId: String) {
    // Called when the user taps the ad.
}

func nativeAdDidError(_ placementId: String, withError error: Error) {
    // Called when a runtime error occurs after the ad is loaded.
}
```

{% endcode %}

{% code title="Objective-C" %}

```objectivec
- (void)nativeAdDidLoad:(NSString *)placementId nativeAd:(FYBNativeAd *)nativeAd {
    nativeAd.delegate = self;
    [self renderNativeAd:nativeAd];
}

#pragma mark - FYBNativeAdDelegate

- (void)nativeAdDidShow:(NSString *)placementId impressionData:(FYBImpressionData *)impressionData {
    // Called when the ad impression is recorded.
}

- (void)nativeAdDidClick:(NSString *)placementId {
    // Called when the user taps the ad.
}

- (void)nativeAdDidError:(NSString *)placementId withError:(NSError *)error {
    // Called when a runtime error occurs after the ad is loaded.
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

#### For a Scrollable List

The listener and its `onShow` / `nativeAdDidShow` callback are set inside the same function that binds the ad rather than as a separate step. The callback triggers the next request for the placement. For more information, see [Bind the Ad to the View](#bind-the-ad-to-the-view).

### Destroy the Ad <a href="#destroy-the-ad" id="destroy-the-ad"></a>

When an ad is no longer needed, release it so its view and partner SDK resources are freed. Destroy timing differs between a single ad slot and a scrollable list.

#### For a Single Ad Slot

{% tabs %}
{% tab title="Android" %}
Remove the view from its container and call `nativeAdView.destroy()`, which also destroys the bound `NativeAd`.

If a `NativeAd` was loaded but never bound to a `NativeAdView`, call `nativeAd.destroy()` directly to free its resources. For example, this can happen if the load callback arrives after the screen is already gone.

{% code title="Kotlin" %}

```kotlin
binding.adContainer.removeAllViews()
nativeAdView.destroy()   // also destroys the bound NativeAd

// Android only. NativeAd loaded but never bound to a view:
nativeAd.destroy()
```

{% endcode %}

{% code title="Java" %}

```java
binding.adContainer.removeAllViews();
nativeAdView.destroy();  // also destroys the bound NativeAd

// Android only. NativeAd loaded but never bound to a view:
nativeAd.destroy();
```

{% endcode %}
{% endtab %}

{% tab title="iOS" %}
Releasing the view is enough. Explicit teardown is usually unnecessary on iOS: `FYBNativeAdView` automatically destroys its bound ad upon deallocation (`dealloc`), so the ad is released as soon as you remove the view from the view hierarchy and release all references to it (or when the hosting view controller is dismissed).

`FYBNativeAd` has no `destroy()` method. An ad that was loaded but never bound to a view is released when you drop your reference to it.

To release partner SDK resources before the view deallocates (such as when its row is recycled in a feed), call `destroy()` explicitly:

{% code title="Swift" %}

```swift
// Optional. Destroy the ad once it is no longer used:
nativeAdView.destroy()
```

{% endcode %}

{% code title="Objective-C" %}

```objectivec
// Optional. Destroy the ad once it is no longer used:
[self.nativeAdView destroy];
```

{% endcode %}
{% endtab %}
{% endtabs %}

#### For a Scrollable List

Destroy a row's ad when the row is recycled, since a row, unlike a single slot, can be reused many times before the screen closes. A row that scrolls back into view shows the next ready ad. On screen exit, also destroy any ad still sitting in the `readyAds` map built in [Bind the Ad to the View](#bind-the-ad-to-the-view), since it was loaded but never bound to a row.

{% tabs %}
{% tab title="Android" %}
{% code title="Kotlin" %}

```kotlin
// In your RecyclerView.Adapter (NativeAdViewHolder and readyAds defined in "Bind the Ad to the View"):
override fun onViewRecycled(holder: RecyclerView.ViewHolder) {
    super.onViewRecycled(holder)
    if (holder is NativeAdViewHolder) {
        holder.destroyAdView()
    }
}

override fun onDestroyView() {
    binding.recyclerView.adapter = null       // Recycles every row, which destroys its ad
    readyAds.values.forEach { it.destroy() }  // Loaded but never bound
    readyAds.clear()
    super.onDestroyView()
}
```

{% endcode %}

{% code title="Java" %}

```java
// In your RecyclerView.Adapter (NativeAdViewHolder and readyAds defined in "Bind the Ad to the View"):
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
    super.onViewRecycled(holder);
    if (holder instanceof NativeAdViewHolder) {
        ((NativeAdViewHolder) holder).destroyAdView();
    }
}

@Override
public void onDestroyView() {
    binding.recyclerView.setAdapter(null); // Recycles every row, which destroys its ad
    for (NativeAd nativeAd : readyAds.values()) {
        nativeAd.destroy(); // Loaded but never bound
    }
    readyAds.clear();
    super.onDestroyView();
}
```

{% endcode %}
{% endtab %}

{% tab title="iOS" %}
No teardown is needed when the screen closes. Cells are deallocated automatically, and `NativeAdCell.prepareForReuse` (defined in [Bind the Ad to the View](#bind-the-ad-to-the-view)) destroys each ad on recycle.
{% endtab %}
{% endtabs %}

## Ad Properties

A loaded `NativeAd` / `FYBNativeAd` exposes the following properties:

| Property                      | Android (`NativeAd`)                     | iOS (`FYBNativeAd`)                         |
| ----------------------------- | ---------------------------------------- | ------------------------------------------- |
| Headline                      | `title: String?`                         | `title: String?`                            |
| Body text                     | `body: String?`                          | `body: String?`                             |
| Call-to-action label          | `callToAction: String?`                  | `callToAction: String?`                     |
| Advertiser name               | `advertiser: String?`                    | `advertiser: String?`                       |
| Store name                    | `store: String?`                         | `store: String?`                            |
| Price                         | `price: String?`                         | `price: String?`                            |
| Star rating                   | `starRating: Double?`                    | `starRating: NSNumber?`                     |
| Media aspect ratio            | `mediaAspectRatio: Float?`               | `mediaAspectRatio: NSNumber?`               |
| Impression data               | `impressionData: ImpressionData`         | `impressionData: FYBImpressionData?`        |
| Icon (visual)                 | Loaded into `NativeAdView.iconView`      | Loaded into `FYBNativeAdView.iconView`      |
| Media (image or video visual) | Loaded into `NativeAdView.mediaView`     | Loaded into `FYBNativeAdView.mediaView`     |
| AdChoices (visual)            | Loaded into `NativeAdView.adChoicesView` | Loaded into `FYBNativeAdView.adChoicesView` |

Text properties are nullable strings. Guard them before displaying, and if the value is `null` / `nil`, hide the UI slot.

## Asset Availability by Network

Not all networks provide the same assets. The table below shows the assets each mediated network provides and which assets are guaranteed regardless of the specific fill.

{% hint style="warning" %}
Google GAM does not support native ads, and GAM placements do not serve native fills. Google AdMob and GMA NextGen both support native ads but use different underlying SDKs. Google AdMob is included in the core `fairbid-sdk`, while GMA NextGen requires the separate `fairbid-sdk-adapter-nextgen` module.
{% endhint %}

| Asset          |  DT Exchange |    Pangle    | Google AdMob | GMA NextGen |
| -------------- | :----------: | :----------: | :----------: | :---------: |
| Title          |       ✓      |       ✓      |       ✓      |      ✓      |
| Body           |   Per fill   |       ✓      |   Per fill   |   Per fill  |
| Call to action |   Per fill   |       ✓      |       ✓      |      ✓      |
| Icon           | Per fill[^1] | Per fill[^2] |   Per fill   |   Per fill  |
| Media view     |       ✓      | Per fill[^2] |       ✓      |      ✓      |
| AdChoices      |   Automatic  |       ✓      |   Automatic  |  Automatic  |
| Advertiser     |   Per fill   |       ✗      |   Per fill   |   Per fill  |
| Star rating    |   Per fill   |       ✗      |   Per fill   |   Per fill  |
| Store          |       ✗      |       ✗      |   Per fill   |   Per fill  |
| Price          |   Per fill   |       ✗      |   Per fill   |   Per fill  |

The table uses the following symbols to indicate asset availability:

* ✓: Asset always present.
* Per fill: Asset present for some creatives, `null` for others.
* Automatic: AdChoices rendered automatically by the adapter inside the media view.
* ✗: Asset never provided by this network.

### Minimum View Sizes

| Network                    | View                       | Minimum size                                                               |
| -------------------------- | -------------------------- | -------------------------------------------------------------------------- |
| Google AdMob / GMA NextGen | Media view                 | If the view is smaller than 120 × 120 dp / pt, video fills are not served. |
| Google AdMob / GMA NextGen | Any sub-view within the ad | Below 32 × 32 dp / pt, ads are not served.                                 |
| All networks               | AdChoices container        | 15 × 15 dp / pt. Do not overlap or resize below this.                      |

## Design Guidelines

Follow these guidelines to keep native ads visually consistent with your app while remaining clearly identifiable as ads.

### Match Your App Style

Use your own fonts, colors, and corner radii. The goal is for the ad to feel like a natural part of your content. Never disguise it as content. Keep the following guidelines in mind:

* Do not distort asset aspect ratios, particularly the icon and media view.
* Maintain adequate spacing between the ad and surrounding content items.
* Use a contrasting color for the CTA button. The CTA text comes from the ad creative. Do not override it.

### Label Every Ad

Every native ad must include a clearly visible disclosure (for example, "Ad", "Sponsored", or equivalent) according to each network's guidelines. Do not rely on the creative itself to supply this label.

### AdChoices is Mandatory

Always include an `adChoicesView` container in your layout. Displaying the AdChoices icon is required for all networks. How it is populated depends on the following network behavior:

* Pangle: the SDK loads the AdChoices icon directly into your `adChoicesView` container.
* DT Exchange, Google AdMob, GMA NextGen: the adapter renders AdChoices automatically inside the media view. For these networks, your `adChoicesView` container receives no content and appears empty. However, you must still provide the container so it is present if a different network serves.

## Placement Guidelines

Where you place a native ad affects both user experience and performance. Depending on your layout, use the following guidelines.

* Avoid the following practices that reduce user trust and ad performance:
  * Do not display a native ad immediately on app launch without user context.
  * Do not place a native ad inside another ad container.
  * Do not design native ad views to mimic system UI elements like navigation bars, status bars, or buttons.
* Space placements apart. Make sure two ads using the same placement ID are never on screen at the same time.
* Tear down ads cleanly. For more information, see [Destroy the Ad](#destroy-the-ad).
* If you use a fixed slot, for example, between paragraphs or at the bottom of a detail screen, visually separate it from editorial content with spacing or a divider line.

## Testing and Monitoring

Before going live, verify your placements with the FairBid [Test Suite](/dt-fairbid/fairbid-sdk/tools/test-suite.md) and confirm that your integration meets the following criteria:

* All ad assets render correctly and at the right size on all target devices.
* The AdChoices icon is never clipped or obscured.

After launch, use the [DT Console](https://console.digitalturbine.com) reporting dashboards to monitor the following metrics:

* Fill rate. Low fill may indicate a misconfigured placement or missing network adapters.
* Bind-to-impression ratio. If binds consistently exceed impressions, verify that `adChoicesView` is assigned and visible as some networks gate impressions on view presence.
* eCPM. Native eCPMs vary by format and network. Allow a ramp-up period before benchmarking against other formats.

[^1]: DT Exchange can serve a minimal creative consisting of title and media view only. Always guard the contents of `iconView`, and if it is `null`, hide the icon slot.

[^2]: Pangle uses two creative types determined at load time: a video fill provides title + media view (icon may also be present but is not required to display it); an image fill provides title, icon, and media view where at least one icon or media view must be displayed. Always guard both `iconView` and `mediaView` content.


---

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

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

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

```
GET https://docs.digitalturbine.com/dt-fairbid/fairbid-sdk/ad-formats/native-ads.md?ask=<question>&goal=<user_goal>
```

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

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

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