Build SDK Mediation Adapters for iOS

Write custom events to support custom ad networks not listed on our Supported Mediation Partners page.

Disclaimer: MoPub cautions usage of non-supported network adapters and does not provide testing or technical support for issues arising from usage. Supported network adatpers can be found at the link above.

Quick Start for Adapter Configuration

To support MoPub SDK 5.5.0+, you must implement an adapter configuration class to enable an interface between your custom event and the MoPub SDK. This interface faciliates a pre-initialization of your SDK, and can be written using the steps below:

Create a new .m and .h class in your project. The name of this class should contain your ad network name, and it should end with AdapterConfiguration.

In your adapter configuration header file:

  1. Import and interface MPBaseAdapterConfiguration.h. Doing so provides adapter information back to the MoPub SDK and serves as the main access point for all adapter-level configuration.
  2. Declare the following properties that will be accessed and defined in the implementation file:
     @property (nonatomic, copy, readonly) NSString * adapterVersion;
     @property (nonatomic, copy, readonly) NSString * biddingToken;
     @property (nonatomic, copy, readonly) NSString * moPubNetworkName;
     @property (nonatomic, copy, readonly) NSString * networkSdkVersion;
    
  3. Declare + (void)updateInitializationParameters:(NSDictionary *)parameters. When invoked in the implementation file, this method extracts parameters used for network SDK initialization, and updates the cache (if they are present). This method directly calls MoPub’s setCachedInitializationParameters:configuration with an NSDictionary, so you might choose to use the latter.
  4. Declare - (void)initializeNetworkWithConfiguration:(NSDictionary<NSString *, id> * _Nullable)configuration complete:(void(^ _Nullable)(NSError * _Nullable))complete. When overriden in the implementation file, this method initializes the network SDK. This logic executes alongside the initialization of the MoPub SDK.

In your adapter configuration implementation file:

  1. Import and implement your adapter configuration header file.
  2. Override - (NSString *)adapterVersion and return the version number of your adapter or custom event. All MoPub’s adapters and custom events use a 4-digit versioning scheme, of which the leftmost 3 digits correspond to the network SDK version, and the last digit denotes the minor version number referring to an adapter release.
  3. Override - (NSString *)biddingToken and return the bidding token String from your ad network. If your ad network does not support Advanced Bidding, return nil.
  4. Override - (NSString *)moPubNetworkName and return a lowercase String that represents your ad network name. Use underscores if the String needs to contain spaces.
  5. Override - (NSString *)networkSdkVersion and return the version number of your ad network SDK.
  6. Override the - (void)initializeNetworkWithConfiguration:(NSDictionary<NSString *, id> *)configuration complete:(void(^)(NSError *))complete method and implement code that initializes your network SDK. Ensure that your custom event always notifies the complete block afterwards.
    • If initialization succeeds, call complete(nil).
    • If initialization fails, call complete(error) that accepts an NSError object.
  7. Optional: If your custom event caches network IDs after a successful ad request, implement the below logic to retain and reuse the data:
    • Import your adapter configuration to a custom event (e.g. interstitial).
    • When your custom event has validated the network IDs returned from the server, call updateInitializationParameters:info on your adapter configuration instance with info being the NSDictionary containing the network parameters.
    • Back to your adapter configuration implementation file, override + (void)updateInitializationParameters:(NSDictionary *)parameters and call MoPub’s setCachedInitializationParameters:configuration with configuration being the NSDictionary containing the network parameters.

Quick Start for Adapter Logging

To support MoPub SDK 5.5.0+, you must implement the new logging API to be consistent with MoPub as well as mediation SDKs. When the new API is used, you will have access to more expressive and constructive logs that can help with debugging purposes. Follow the steps outlined below to add logging to your custom events:

  1. Ensure that your custom events are not using any legacy/custom log and/or iOS’ NSLog APIs.
  2. For each of the ad’s lifecycle events that happens, your custom event will log it by invoking MPLogAdEvent. The call accepts an official interface instancetype (representing the event), followed by different macros representing the additional data to be logged. For example, after an ad request, your custom event should log an adShowAttemptForAdapter occurrence: MPLogAdEvent([MPLogEvent adShowAttemptForAdapter:NSStringFromClass(self.class)], [self getAdNetworkId]). For the comprehensive list of the events as well as the macros, check out the MPLogEvent interface from the SDK: [LINK]. Your custom events should make use of as many such enum constants as they see fit.
  3. For any other generic messages that need to be logged, your custom event will use the MPLogInfo API, followed by a String containing the message. For example: MPLogInfo(@"Ad view created.").

Quick Start for Banners

  1. Create a subclass of MPBannerCustomEvent in your application.

  2. Override the -requestAdWithSize:customEventInfo: method and implement code that requests an ad.

  3. When your ad loads successfully, you must notify MoPub of the event by calling the -bannerCustomEvent:didLoadAd: method on the custom event object’s delegate (accessible via the delegate property).

  4. Similarly, you must notify the delegate when your ad fails to load by calling -bannerCustomEvent:didFailToLoadAdWithError: method.

  5. (Optional) Notify the delegate of user interaction events via the corresponding delegate methods:

    -bannerCustomEventWillBeginAction: -bannerCustomEventDidFinishAction: adViewWillLogImpression

    NOTE: If your implementation calls -bannerCustomEventWillBeginAction:, it must also call -bannerCustomEventDidFinishAction:.

  6. (Optional) Notify the delegate if the user leaves the application from a banner via the -bannerCustomEventWillLeaveApplication: method.

  7. (Optional) Implement the -dealloc method if your custom event requires any sort of cleanup.

  8. Finally, in the MoPub web UI, create a network with the “Custom SDK Network” type. Place the class name of your custom event (e.g. YourBannerCustomEvent) in the “Custom Class” column.

Once you’ve completed these steps, the MoPub SDK will be able to automatically instantiate your MPBannerCustomEvent subclass when your application is running. You do not need to instantiate any of these subclasses in your application code.

Note: the MoPub SDK will instantiate a new MPBannerCustomEvent object on every ad call, so you can safely make changes to the custom event object’s internal state without affecting subsequent ad calls.

Quick Start for Interstitials

  1. Create a subclass of MPInterstitialCustomEvent in your application.

  2. Override the -requestInterstitialWithCustomEventInfo: method and implement code that requests an interstitial.

  3. Override the -showInterstitialFromRootViewController: and implement code that displays your interstitial.

  4. You must notify MoPub of all of the following interstitial lifecycle events, by calling the corresponding methods on the custom event object’s delegate (accessible via the delegate property):

     -interstitialCustomEvent:didLoadAd:
     -interstitialCustomEvent:trackImpression:
     -interstitialCustomEvent:didFailToLoadAdWithError:
     -interstitialCustomEventWillAppear:
     -interstitialCustomEventDidAppear:
     -interstitialCustomEventWillDisappear:
     -interstitialCustomEventDidDisappear:
    

    All of the methods above are required. If the ad network you are trying to use does not provide callbacks for one/more of these events, you should still call the custom event method at an appropriate time.

    For example, if an ad network only provides an adDidDisappear callback, your custom event should fire both -interstitialCustomEventWillDisappear: and -interstitialCustomEventDidDisappear: in response.

  5. (Optional) If the ad network is capable of notifying you when a user interacts or taps on an ad, you should forward this information to the MoPub SDK so that MoPub can provide accurate analytics. You can do so by calling the interstitialCustomEventDidReceiveTapEvent: method on the custom event delegate.

  6. (Optional) Implement the -dealloc method if your custom event requires any sort of cleanup.

  7. Finally, on the MoPub web interface, create a network with the “Custom SDK Network” type. Place the class name of your custom event (e.g. YourInterstitialCustomEvent) in the “Custom Class” column.

Once you’ve completed these steps, the MoPub SDK will be able to automatically instantiate your MPInterstitialCustomEvent subclass when your application is running. You do not need to instantiate any of these subclasses in your application code.

Note: the MoPub SDK will instantiate a new MPInterstitialCustomEvent object on every ad call, so you can safely make changes to the custom event object’s internal state without affecting subsequent ad calls.

Quick Start for Rewarded Video

  1. Create a subclass of MPRewardedVideoCustomEvent in your application.

  2. Override the -requestRewardedVideoWithCustomEventInfo: method and implement code that requests a rewarded interstitial.

  3. Override the -hasAdAvailable: and implement code that displays your rewarded interstitial.

  4. Override the -presentRewardedVideoFromViewController: and implement code that displays your rewarded interstitial.

  5. You must notify MoPub of all of the following rewarded interstitial lifecycle events, by calling the corresponding methods on the custom event objects delegate (accessible via the delegate property):

     -rewardedVideoDidLoadAdForCustomEvent:
     -rewardedVideoDidFailToLoadAdForCustomEvent:
     -rewardedVideoDidExpireForCustomEvent:
     -rewardedVideoDidFailToPlayForCustomEvent:
     -rewardedVideoWillAppearForCustomEvent:
     -rewardedVideoDidAppearForCustomEvent:
     -rewardedVideoWillDisappearForCustomEvent:
     -rewardedVideoDidDisappearForCustomEvent:
     -rewardedVideoWillLeaveApplicationForCustomEvent:
     -rewardedVideoDidReceiveTapEventForCustomEvent:
     -rewardedVideoShouldRewardUserForCustomEvent:
    
  6. Override -enableAutomaticImpressionAndClickTracking: if you as a network want to handle the impression and click tracking, please use -trackImpression: and -trackClick: respectively.

  7. (Optional) The other optional methods to override are -handleAdPlayedForCustomEventNetwork: and -handleCustomEventInvalidated:

  8. (Optional) Implement MPMediationSettingsProtocol marker interface if you want to enable publishers to pass any network specific additional parameters during the initialization

Quick Start For Native Ads

  1. Create a class that implements the MPNativeAdAdapter protocol. This class will act as an adapter between the ‘MPNativeAd’ interface and your custom SDK ad network.

  2. Create an initialization method that takes in the your network’s native ad as a parameter. In addition to retaining this in a property, you also need to map its content to a dictionary properties. The keys you need to use can be found in MPNativeAdConstants.h, and include:

    • kAdTitleKey for a title string
    • kAdTextKey for a description or body text
    • kAdIconImageKey for an icon-sized image
    • kAdMainImageKey for a larger image
    • kAdCTATextKey for a call to action string
    • kAdStarRatingKey for a star rating (that needs to be normalized to a 0-5 scale).

    Another necessary property to implement is the defaultActionURL - the URL the user is taken to when they interact with the ad. If the native ad automatically opens it then this can be nil.

    Any additional content can be placed in the properties dicitonary at your discretion, which will allow you to access it through the MPNativeAd interface.

  3. Implement the method displayContentForURL:rootViewController:completion:. This method is called when the user interacts with your ad, and can either forward the call to a corresponding method on the mediated ad, or you can implement URL-opening yourself. You do not need to implement this method if your ad network automatically handles taps on your ad.

  4. (Optional) The MPNativeAdAdapter protocol also has a number of optional methods that can be implemented to allow for further customization and passing behavior back to the mediated ad.

    • willAttachToView: is called when the ad content is loaded into its container view, and passes back that view. Native ads that automatically track impressions should implement this method.
    • trackClick is called when the user interacts with an ad, and allows for manual click tracking for the mediated ad.
  5. Create a class that conforms to the MPNativeAdRendererSettings protocol.

  6. Expose the viewSizeHandler property on your class so the ad can be properly sized when used with an ad placer product.

     @property (nonatomic, readonly) MPNativeViewSizeHandler viewSizeHandler;
    

    Add any additional properties to the class that can be configured by the application.

  7. Create a class that conforms to the MPNativeAdRenderer protocol. Expose the viewSizeHandler property on this object as well.

  8. Implement rendererConfigurationWithRendererSettings:.

     + (MPNativeAdRendererConfiguration *)rendererConfigurationWithRendererSettings:(id<MPNativeAdRendererSettings>)rendererSettings
    

    Create an MPNativeAdRendererConfiguration object by setting the rendering class to your class that conforms to the MPNativeAdRenderer protocol. Set the configuration object’s rendererSettings property to the rendererSettings parameter. Finally, specify which custom events your renderer supports by setting the supportedCustomEvents property to an array that contains the name of your class that is a subclass of MPNativeCustomEvent outlined in step 11.

  9. Implement initWithRendererSettings:. Set your object’s viewSizeHandler to the viewSizeHandler in the rendererSettings parameter. Extract any custom settings properties from your rendererSettings here or simply keep a reference to the renderer settings in your class if you need them to render your ad view.

  10. Implement retrieveViewWithAdapter:. Return a view that contains the rendered ad elements using the data contained in your adapter class. You should recreate the view each time this is called if possible.

  11. Create a subclass of MPNativeCustomEvent.

  12. Override the requestAdWithCustomEventInfo: method and implement code that requests an ad. The info NSDictionary passed to this method is defined in the custom SDK network set up on app.mopub.com under Custom Event Class Data. It should include any necessary information for requesting an ad on your network such as ad unit ID.

  13. When the ad returns, you need to create a corresponding object that adheres to the MPNativeAdAdapter protocol (as described in previous steps), and use that to create an MPNativeAd with the initWithAdAdapter: initializer.

  14. Before calling customNativeEvent:didLoadAd: on the custom event’s delegate, call the superclass’s precacheImagesWithURLs:completionBlock: method to download and cache the images that will be shown in the ad (typically the icon and main image). At that point, the delegate can receive the MPNativeAd object.

  15. If at any point an error occurs loading the mediated ad or its images, call nativeCustomEvent:didFailToLoadAdWithError: on the inherited delegate.

Passing Extra Data To Custom Events

In the banner, interstitial and rewarded video custom event subclasses, the methods called to load an ad include an NSDictionary parameter (called info) that you may use to provide your custom event with any additional data it needs.

The info object is populated with data entered in the MoPub web interface. Specifically, after navigating to the Custom SDK Network edit page, you can select the “Custom Event Class Data” column and enter a JSON object with String keys and values in the Data field (e.g. {"id": "12345", "foo": "bar"}). This is particularly useful for passing down third-party Network IDs without making changes to your application code.

Impression and Click Tracking

Banner and Interstitial Ads

The MoPub SDK will automatically record impressions and clicks for custom events in response to certain delegate callbacks.

For banner custom events, impressions are recorded on -bannerCustomEvent:didLoadAd:, and clicks are recorded on -bannerCustomEventWillBeginAction: or -bannerCustomEventWillLeaveApplication:.

For interstitial custom events, impressions are recorded on -interstitialCustomEventDidAppear:, and clicks are recorded on -interstitialCustomEventDidReceiveTapEvent:.

If you require more control over when impressions and clicks are recorded, you may override the default behavior in your custom event by overriding -(BOOL)enableAutomaticImpressionAndClickTracking and returning NO. You can then manually report impressions and clicks by calling -trackImpression and -trackClick on the custom event delegate.

Native Ads

The MPNativeAdAdapter protocol provides flexible methods that allow for easy click and impression tracking.

If the mediated ad requires manual click tracking, provide an implementation for trackClick. The MPNativeAd will call this method automatically when appropriate.

If the mediated ad automatically handles clicks, implement -enableThirdPartyClickTracking and return NO. When your ad does track a click, you must call -nativeAdDidClick on your adapter’s delegate.

If the mediated ad requires manual impression tracking, you must determine when your adapter tracks an impression and call -nativeAdWillLogImpression: on your adapter’s delegate.

If the mediated ad already provides automatic impression tracking, the willAttachToView: method allows the adapter to pass the corresponding UIView to the mediated ad. You must call -nativeAdWillLogImpression: on your adapter’s delegate when your adapter is notified that an impression has been tracked by the 3rd party SDK.

Last updated August 26, 2019

TWITTER, MOPUB, and the Bird logo are trademarks of Twitter, Inc. or its affiliates. All third party logos and trademarks included are the property of their respective owners.

© 2019 MoPub (a division of Twitter, Inc.)