> 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/native-ad.md). Agents can also search and read this documentation through its [MCP server](https://ios-docs.adster.tech/~gitbook/mcp).

# Native Ad

To receive 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

AdSter video ads expose `nativeAd.videoController`; it may be nil for images or other networks. Keep the SDK media view attached. Video starts muted with SDK controls, aspect fit and automatic visibility handling.

```swift
if let video = nativeAd.videoController {
    video.scaleMode = .aspectFit
    video.customControlsEnabled = true // Only when supplying your own controls.
    video.listener = videoListener // Retain this listener in your view/controller.
}
```

`.aspectFit` shows the whole video, `.aspectFill` crops to fill, and `.fill` stretches. Custom controls hide the SDK controls and disable its playback tap. Bind your buttons to `play()`, `pause()`, `mute()`, `unmute()` and `replay()`. For a custom CTA overlay, call `adView.performClick()` to preserve click tracking and navigation.

Implement only the `AdSterVideoListener` callbacks you need: ready, playback, buffering, sound, quartiles, progress and failure. Use `onProgress(currentTimeMs:durationMs:)` for a progress bar or countdown; times are milliseconds. Read `isBuffering`, `isCompleted`, `videoWidth`, `videoHeight` and `aspectRatio` for UI state. Metadata is zero or nil until ready.

Use the controller on the main thread; callbacks also arrive there. The listener is weak, so retain it and clear it on disposal. Leave `automaticVisibilityEnabled` enabled unless your app manages visibility and background pause/resume. Replay restarts the same creative without a new impression or revenue event. Use `native_video_test` to test native video.

**Implementation:**

```swift
extension NativeAdManager: MediationAdDelegate {
    func onNativeAdLoaded(nativeAd: AdsFramework.MediationNativeAd) {
        nativeAd.eventDelegate = self
        guard let nibObjects = Bundle.main.loadNibNamed("NativeView", owner: nil, options: nil),
              let adView = nibObjects.first as? MediationNativeAdView else {
            printLog("Could not load nib file for adView")
            return
        }
        (adView.bodyView as? UILabel)?.text = nativeAd.body
        (adView.headlineView as? UILabel)?.text = nativeAd.headline
        (adView.ctaView as? UIButton)?.setTitle(nativeAd.callToAction, for: .normal)
        (adView.ctaView as? UIButton)?.isUserInteractionEnabled = false
        if let mediaView = nativeAd.mediaView {
            addMediaViewToParentView(childView: mediaView, parentView: adView.mediaView)
        }
        
        adView.setNativeAd(nativeAd: nativeAd)
        viewBanner.addSubview(adView)
    }

    func onAdFailedToLoad(error: AdError) {
        print("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)")
        
    }
}
```

**Embed the SDK media view:**

Use the supplied `nativeAd.mediaView` for both images and video. Connect the XIB's `adView.mediaView` outlet to a container with a defined width and height (for example, 180 points high), and size the ad card to its content. Do not use a full-screen XIB frame as the ad's height. Keep the media view interactive so its playback controls can receive taps.

```swift
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 `MediationNativeAdEventDelegate`:

```swift
extension NativeAdManager: MediationNativeAdEventDelegate {
    func recordNativeClick() {
        print("Native ad clicked")
    }
    
    func recordNativeImpression() {
        print("Native ad impression recorded")
    }
}
```

### Start with sound

To start unmuted, call `unmute()` on the main thread in `onNativeAdLoaded`, 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 onNativeAdLoaded, before displaying the ad:
nativeAd.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
nativeAd.videoController?.pause() // For example, in your app's pause action.
// Later, in your resume action:
// nativeAd.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.

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