> For the complete documentation index, see [llms.txt](https://ios-docs.adster.tech/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ios-docs.adster.tech/ad-types/custom-native-ad.md). Agents can also search and read this documentation through its [MCP server](https://ios-docs.adster.tech/~gitbook/mcp).

# Custom Native Ad

To receive Custom Native Ads, conform to the `MediationAdDelegate` protocol. Once the ad is loaded, you can populate your custom native ad view with the ad's data.

### Video controls

For AdSter video creatives, attach `customNativeAd.mediaView` and use the optional `customNativeAd.videoController`. The [Native Ad video controls](https://ios-docs.adster.tech/ad-types/native-ad) also apply here: aspect fit, custom controls, replay, progress, buffering and playback callbacks.

```swift
customNativeAd.videoController?.scaleMode = .aspectFit
// In your CTA button action:
customNativeAd.performClick(on: "Calltoaction")
```

Keep the SDK media view attached when overlaying controls. Set `customControlsEnabled = true` only when providing your own playback UI, retain your `AdSterVideoListener`, and clear it before destroying the ad. Use the SDK click method for CTA tracking and navigation.

**Implementation:**

```swift
extension CustomNativeAdManager: MediationAdDelegate {
    func onCustomNativeAdLoaded(customNativeAd: AdsFramework.MediationNativeCustomFormatAd) {
        customNativeAd.eventDelegate = self
        if customNativeAd.getCustomFormatId() == "123456" {
            // Show native custom format for template ID 123456
            displayNativeCustomFormatAd(customNativeAd)
        } else if customNativeAd.getCustomFormatId() == "654321" {
            // Show native custom format for template ID 654321
            displayNativeCustomFormatAd(customNativeAd)
        } else {
            // Fallback for unknown custom native formats
            displayNativeCustomFormatAd(customNativeAd)
        }
    }

    func onAdFailedToLoad(error: AdError) {
        print("Custom Native Ad request failed with reason \(error.description)")
    }
    
    func onAdRevenuePaid(revenue: Double, adUnitId: String, network: String, currency: String, precisionType: AdsFramework.PrecisionType) {
        print("Revenue: \(revenue) \(currency), adUnitId: \(adUnitId), network: \(network), precision: \(precisionType)")
        
    }
}
```

**Define your custom native ad layout:**

The below layout is an example UIKit view. You can create the same UI in a XIB, storyboard, or in code.

```swift
final class CustomNativeAdView: UIView {
    let mainImageView = UIImageView()
    let mediaContainerView = UIView()
    let titleLabel = UILabel()
    let bodyLabel = UILabel()
    let advertiserLabel = UILabel()
    
    let ctaButton = UIButton(type: .system)
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }

    private func setupView() {
        mainImageView.contentMode = .scaleAspectFill
        mainImageView.clipsToBounds = true
        mainImageView.translatesAutoresizingMaskIntoConstraints = false

        mediaContainerView.translatesAutoresizingMaskIntoConstraints = false

        let textStack = UIStackView(arrangedSubviews: [
            titleLabel,
            bodyLabel,
            advertiserLabel,
            ctaButton
        ])
        textStack.axis = .vertical
        textStack.spacing = 8
        textStack.translatesAutoresizingMaskIntoConstraints = false

        let rootStack = UIStackView(arrangedSubviews: [
            mainImageView,
            mediaContainerView,
            textStack
        ])
        rootStack.axis = .vertical
        rootStack.spacing = 12
        rootStack.translatesAutoresizingMaskIntoConstraints = false

        addSubview(rootStack)

        NSLayoutConstraint.activate([
            rootStack.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
            rootStack.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
            rootStack.topAnchor.constraint(equalTo: topAnchor, constant: 16),
            rootStack.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -16)
        ])

        // Allow UIStackView to collapse the unused media/image slot.
        let imageHeight = mainImageView.heightAnchor.constraint(equalToConstant: 180)
        let mediaHeight = mediaContainerView.heightAnchor.constraint(equalToConstant: 190)
        imageHeight.priority = .defaultHigh
        mediaHeight.priority = .defaultHigh
        NSLayoutConstraint.activate([imageHeight, mediaHeight])

        titleLabel.font = .boldSystemFont(ofSize: 18)
        bodyLabel.font = .systemFont(ofSize: 14)
        advertiserLabel.font = .systemFont(ofSize: 13)
        advertiserLabel.textColor = .secondaryLabel
    }
}
```

**Use the `MediationNativeCustomFormatAd` object to populate your custom native layout.:**

The asset names depend on your GAM custom native format. The example below uses common asset names such as `Headline`, `Body`, `Calltoaction`, and `Attribution`.

```swift
private func displayNativeCustomFormatAd(_ ad: AdsFramework.MediationNativeCustomFormatAd) {
    let adView = CustomNativeAdView()

    adView.titleLabel.text = ad.getText(for: "Headline")
    adView.bodyLabel.text = ad.getText(for: "Body")
    adView.advertiserLabel.text = ad.getText(for: "Attribution")
    adView.ctaButton.setTitle(ad.getText(for: "Calltoaction"), for: .normal)

    adView.ctaButton.addAction(UIAction { [weak ad] _ in
        ad?.performClick(on: "Calltoaction")
    }, for: .touchUpInside)

    // Add the custom native view to your container.
    // `adContainerView` is a UIView you have added to your view controller.
    adContainerView.addSubview(adView)
    adView.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
        adView.leadingAnchor.constraint(equalTo: adContainerView.leadingAnchor),
        adView.trailingAnchor.constraint(equalTo: adContainerView.trailingAnchor),
        adView.topAnchor.constraint(equalTo: adContainerView.topAnchor),
        adView.bottomAnchor.constraint(equalTo: adContainerView.bottomAnchor)
    ])

    // Render SDK media, Google media content, or an image fallback.
    renderImageAndMediaAssets(for: ad, into: adView)
    
    // Start viewability tracking for AD_VIEWABLE_IMPRESSION / AD_VIEWABLE_IMPRESSION_FAILURE.
    // Pass the root custom native ad view.
    ad.trackViewability(adView)

    // Record an impression when your custom native ad view is visible.
    ad.recordNativeImpression()
}
```

**Render image and media assets:**

First use the optional `ad.mediaView` for Adster and Adster Direct video, including its playback controls. Adster video returns `nil` from `getMediaContent()`; do not use that property to decide whether to render SDK video. If there is no SDK media view, preserve the Google media-content path, then fall back to the image asset. Import `GoogleMobileAds` for `MediaView` and the image/media bridge below; Google's interface is unchanged.

Attach click handlers to the CTA and other clickable assets. Do not put an advertiser-navigation gesture over the video or let a parent gesture consume its playback, mute, or skip taps.

```swift
private func renderImageAndMediaAssets(
    for ad: AdsFramework.MediationNativeCustomFormatAd,
    into adView: CustomNativeAdView
) {
    adView.mainImageView.isHidden = true
    adView.mediaContainerView.isHidden = true

    if let mediaView = ad.mediaView {
        adView.mediaContainerView.isHidden = false
        addMediaViewToParentView(
            childView: mediaView,
            parentView: adView.mediaContainerView
        )
        return
    }

    guard let gamAd = ad as? any MediationNativeCustomFormatAdGAM else { return }

    // Preserve the Google custom-native media path.
    if let mediaContent = gamAd.getMediaContent(),
       mediaContent.hasVideoContent || mediaContent.mainImage != nil {
        let mediaView = MediaView()
        mediaView.contentMode = .scaleAspectFill
        mediaView.clipsToBounds = true
        mediaView.mediaContent = mediaContent
        adView.mediaContainerView.isHidden = false
        addMediaViewToParentView(
            childView: mediaView,
            parentView: adView.mediaContainerView
        )
        return
    }

    // Asset names depend on your format. Adster supports "MainImage"
    // and "Image"; video creatives expose the poster as the image fallback.
    if let nativeImage = gamAd.getImage(for: "MainImage") {
        adView.mainImageView.isHidden = false
        if let uiImage = nativeImage.image {
            adView.mainImageView.image = uiImage
        } else if let url = nativeImage.imageURL {
            // In reusable views, retain/cancel this request when replacing the ad.
            URLSession.shared.dataTask(with: url) { data, _, _ in
                guard let data, let uiImage = UIImage(data: data) else { return }
                DispatchQueue.main.async {
                    adView.mainImageView.image = uiImage
                }
            }.resume()
        }
    }
}

private func addMediaViewToParentView(childView: UIView, parentView: UIView) {
    childView.removeFromSuperview()
    parentView.subviews.forEach { $0.removeFromSuperview() }
    childView.translatesAutoresizingMaskIntoConstraints = false
    parentView.addSubview(childView)
    NSLayoutConstraint.activate([
        childView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor),
        childView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor),
        childView.topAnchor.constraint(equalTo: parentView.topAnchor),
        childView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor)
    ])
}
```

**Tracking Events:**

To track impression and click events for Native Ads, conform to `MediationNativeCustomAdEventDelegate`:

```swift
extension CustomNativeAdManager: MediationNativeCustomAdEventDelegate {
    func recordNativeCustomClick() {
        print("Custom Native ad clicked")
    }
    
    func recordNativeCustomImpression() {
        print("Custom Native ad impression recorded")
    }
    
    func recordNativeCustomClick(ad: AdsFramework.MediationNativeCustomFormatAd, assetName: String) {
        print("Custom native click on asset: \(assetName)")
    }
}
```

{% hint style="info" %}
**If your custom native format can return different asset names, you can inspect the available assets dynamically:**

```swift
let assetNames = customNativeAd.getAvailableAssetNames() ?? []

for assetName in assetNames {
    if let text = customNativeAd.getText(for: assetName), !text.isEmpty {
        print("Text asset: \(assetName) = \(text)")
    }

    if let gamAd = customNativeAd as? any MediationNativeCustomFormatAdGAM,
       let image = gamAd.getImage(for: assetName) {
        print("Image asset: \(assetName), uiImage=\(String(describing: image.image)), url=\(String(describing: image.imageURL))")
    }
}
```

{% endhint %}

### Start with sound

To start unmuted, call `unmute()` on the main thread in `onCustomNativeAdLoaded`, before attaching the ad view. This also stores the choice while the player prepares. Apply it to each newly loaded ad; each starts muted.

```swift
// Inside onCustomNativeAdLoaded, before displaying the ad:
customNativeAd.videoController?.unmute() // Optional: omit to keep the muted default.
```

### Control playback

Use `AdSterVideoController` and its properties on the main thread. Each method below is an independent action for your UI.

| API                   | Behavior                                                                      |
| --------------------- | ----------------------------------------------------------------------------- |
| `play()`              | Resumes a paused video when visible and the app is active.                    |
| `pause()`             | Pauses until `play()` is called or the viewer resumes using the SDK controls. |
| `mute()` / `unmute()` | Changes sound immediately or stores the choice until preparation finishes.    |
| `isPlaying`           | Reports whether the player is currently playing.                              |
| `isMuted`             | Reports the current mute setting.                                             |

```swift
customNativeAd.videoController?.pause() // For example, in your app's pause action.
// Later, in your resume action:
// customNativeAd.videoController?.play()
```

### Lifecycle and cleanup

Retain the loaded ad while it is displayed. On the main thread, call `destroy()` when replacing or permanently removing it, remove its view, and clear your retained reference. Cancel any image requests owned by your app.&#x20;

```swift
// When permanently removing the retained ad, on the main thread:
customNativeAd.destroy()
// Remove its view and clear your retained ad reference.
```
