Build SDK Mediation Adapters for iOS
- Quick Start for Adapter Configuration
- Quick Start for Adapter Logging
- Quick Start for Inline Ads
- Quick Start for Fullscreen Ads
- Quick Start For Native Ads
- Passing Extra Data To Adapters
- Impression and Click Tracking
Write mediation adapters to support custom ad networks not listed on our Supported Mediation Partners list.
Disclaimer: MoPub discourages using non-supported network adapters and does not provide testing or technical support for problems arising from their use. Refer to our list of supported network adapters.
Quick Start for Adapter Configuration
To support MoPub SDK v5.5.0+, you must implement an adapter configuration class to enable an interface between your adapters 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:
-
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. -
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;
-
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’ssetCachedInitializationParameters:configuration
with anNSDictionary
, so you might choose to use the latter. -
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:
-
Import and implement your adapter configuration header file.
-
Override
- (NSString *)adapterVersion
and return the version number of your adapter. All MoPub’s adapters and adapters 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. -
Override
- (NSString *)biddingToken
and return the bidding token String from your ad network. If your ad network does not support Advanced Bidding, returnnil
. -
Override
- (NSString *)moPubNetworkName
and return a lowercase String that represents your ad network name. Use underscores if the String needs to contain spaces. -
Override
- (NSString *)networkSdkVersion
and return the version number of your ad network SDK. -
Override the
- (void)initializeNetworkWithConfiguration:(NSDictionary<NSString *, id> *)configuration complete:(void(^)(NSError *))complete
method and implement code that initializes your network SDK. Ensure that your adapter always notifies thecomplete
block afterwards.-
If initialization succeeds, call
complete(nil)
. -
If initialization fails, call
complete(error)
that accepts anNSError
object.
-
-
Optional: If your adapter caches network IDs after a successful ad request, implement the logic below to retain and reuse the data:
-
Import your adapter configuration to a adapter (e.g. fullscreen ad).
-
When your adapter has validated the network IDs returned from the server, call
updateInitializationParameters:info
on your adapter configuration instance withinfo
being theNSDictionary
containing the network parameters. -
Back to your adapter configuration implementation file, override
+ (void)updateInitializationParameters:(NSDictionary *)parameters
and call MoPub’ssetCachedInitializationParameters:configuration
withconfiguration
being theNSDictionary
containing the network parameters.
-
Quick Start for Adapter Logging
To support MoPub SDK v5.5.0+, you must implement the new logging API to be consistent with MoPub and 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 adapters:
-
Ensure that your adapters are not using any legacy/custom log and/or iOS’
NSLog
APIs. -
For each of the ad’s lifecycle events that happens, your adapter will log it by invoking
MPLogAdEvent
. The call accepts an official interfaceinstancetype
(representing the event), followed by different macros representing the additional data to be logged.-
For example, after an ad request, your adapter 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. Your adapters should make use of as many such enum constants as they see fit.
-
-
For any other generic messages that need to be logged, your adapter will use the
MPLogInfo
API, followed by a String containing the message. For example:MPLogInfo(@"Ad view created.")
.
Quick Start for Inline Ads
This API requires v5.13.0 or newer of the MoPub SDK.
-
Create a subclass of
MPInlineAdAdapter
that implements the<MPThirdPartyInlineAdAdapter>
protocol. -
Override the
requestAdWithSize:(CGSize) adapterInfo: adMarkup:
method and implement code that requests an ad. -
Notify MoPub of inline ad lifecycle events by calling the following methods on the adapter object’s delegate. Failure to do so will disrupt the mediation waterfall and cause future ad requests to stall.
Method When to call inlineAdAdapter:self didLoadAdWithAdView:UIView
After an ad loads succesfully inlineAdAdapter:self didFailToLoadAdWithError:
After an ad fails to load inlineAdAdapterWillBeginUserAction:self
(Optional) When the user taps on the banner ad. If you call this, you must also call inlineAdAdapterDidEndUserAction:self
at a later point.inlineAdAdapterDidEndUserAction:self
(Optional) When the user finishes interacting with the banner ad. You must call this if you call inlineAdAdapterWillBeginUserAction:self
inlineAdAdapterWillLeaveApplication:self
(Optional) When the banner ad will cause the user to leave the application inlineAdAdapterWillExpand:self
(Optional) When the banner ad is expanding or resizing from its default size inlineAdAdapterDidCollapse:self
(Optional) When the banner ad is collapsing back to its default size enableAutomaticImpressionAndClickTracking
(Optional) Return NO
if you want to manually handle impression and click tracking. In that case, useinlineAdAdapterDidTrackImpression:self
andinlineAdAdapterDidTrackClick:self
to track impressions and clicks, respectively -
(Optional) Implement the
dealloc
method if your adapter requires any sort of cleanup. -
Finally, in the MoPub web UI, create a network with the “Custom SDK Network” type. Place the class name of your adapter (e.g.
YourInlineAdAdapter
) in the “Custom Class” column.
Once you’ve completed these steps, the MoPub SDK will be able to automatically instantiate your MPInlineAdAdapter
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 MPInlineAdAdapter
object on every ad call, so you can safely make changes to the adapter object’s internal state without affecting subsequent ad calls.
Quick Start for Fullscreen Ads
This API requires v5.13.0 or newer of the MoPub SDK.
-
Create a subclass of
MPFullscreenAdAdapter
that implements the<MPThirdPartyFullscreenAdAdapter>
protocol. -
Override the
requestAdWithAdapterInfo:(NSDictionary *) adMarkup:
method and implement code that requests a fullscreen ad. -
Override the
isRewardExpected
method. ReturnNO
if a reward is not expected upon completing the ad experience. Otherwise, returnYES
if a reward is expected. -
Override the
hasAdAvailable
method and implement code that checks for the availability of your fullscreen ad. -
Override the
presentAdFromViewController:(UIViewController *)viewController
method and implement code that displays your fullscreen ad. -
Notify MoPub of fullscreen ad lifecycle events by calling the following methods on the adapter object’s delegate. Failure to do so will disrupt the mediation waterfall and cause future ad requests to stall.
Method When to call fullscreenAdAdapterDidLoadAd:self
After an ad loads succesfully fullscreenAdAdapter:self didFailToLoadAdWithError:NSError
After an ad fails to load fullscreenAdAdapterAdWillAppear:self
When an ad is about to appear fullscreenAdAdapterAdDidAppear:self
When an ad has finished appearing fullscreenAdAdapterAdWillDisappear:self
When an ad is about to disappear fullscreenAdAdapterAdDidDisappear:self
When an ad has finished disappearing fullscreenAdAdapterAdDidDismiss:self
When an ad has has been dismissed. Call this after the adapter has called fullscreenAdAdapterAdDidDisappear:self
. Introduced in v5.15.0 of the MoPub iOS SDKfullscreenAdAdapterDidExpire:self
(Optional) If a previously loaded fullscreen ad should no longer be eligible for presentation fullscreenAdAdapterWillLeaveApplication:self
(Optional) When the fullscreen ad will cause the user to leave the application fullscreenAdAdapter:self didFailToShowAdWithError:NSError
(Optional) When the application has attempted to show an ad and it cannot be shown fullscreenAdAdapterDidReceiveTap:self
(optional) When the user taps on the fullscreen ad. Some networks provide a “will leave application” callback instead of/in addition to a “user did click” callback. You should call this method in response to either of those callbacks (since leaving the application is generally an indicator of a user tap) fullscreenAdAdapter:self willRewardUser:reward
(Optional) When the user should be rewarded. If the concept of currency type doesn’t exist for the ad network, set the reward’s currency type to MPRewardCurrencyTypeUnspecified enableAutomaticImpressionAndClickTracking
(Optional) Return NO
if you want to manually handle impression and click tracking. In that case, usefullscreenAdAdapterDidTrackImpression:self
andfullscreenAdAdapterDidTrackClick:self
to track impressions and clicks, respectively -
To clean up after the ad has finished showing, override the following methods:
Method What to do dealloc
Clean up your ad instance and release system resources (e.g. setting the ad and ad unit ID to nil) handleDidPlayAd
Handle when an ad was played for this network, but under a different ad unit ID. This method will only be called if your adapter has reported that an ad had successfully loaded. If the adapter no longer has an ad available, report back up to the application that this ad has expired. handleDidInvalidateAd
Handle when the adapter itself is no longer needed. It is expected you will need to override this method to prevent memory leaks by setting the delegate to nil
. It is safe to override with nothing if you believe you will not leak memory. -
(Optional) Implement
MPMediationSettingsProtocol
marker interface if you want to enable publishers to pass any network specific additional parameters during initialization. -
Finally, on the MoPub web interface, create a network with the “Custom SDK Network” type. Place the class name of your adapter (e.g.
YourFullscreenAdAdapter
) in the “Custom Class” column.
Once you’ve completed these steps, the MoPub SDK will be able to automatically instantiate your MPFullscreenAdAdapter <MPThirdPartyFullscreenAdAdapter>
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 MPFullscreenAdAdapter <MPThirdPartyFullscreenAdAdapter>
object on every ad call, so you can safely make changes to the adapter object’s internal state without affecting subsequent ad calls.
Quick Start For Native Ads
-
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. -
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 inMPNativeAdConstants.h
, and include:kAdTitleKey
for a title stringkAdTextKey
for a description or body textkAdIconImageKey
for an icon-sized imagekAdMainImageKey
for a larger imagekAdCTATextKey
for a call to action stringkAdStarRatingKey
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 theMPNativeAd
interface. -
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. -
(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.
-
-
Create a class that conforms to the
MPNativeAdRendererSettings
protocol. -
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.
-
Create a class that conforms to the
MPNativeAdRenderer
protocol. Expose theviewSizeHandler
property on this object as well. -
Implement
rendererConfigurationWithRendererSettings:
.+ (MPNativeAdRendererConfiguration *)rendererConfigurationWithRendererSettings:(id<MPNativeAdRendererSettings>)rendererSettings
Create an
MPNativeAdRendererConfiguration
object by setting the rendering class to your class that conforms to theMPNativeAdRenderer
protocol. Set the configuration object’srendererSettings
property to therendererSettings
parameter. Finally, specify which adapters your renderer supports by setting thesupportedCustomEvents
property to an array that contains the name of your class that is a subclass ofMPNativeCustomEvent
outlined in step 11. -
Implement
initWithRendererSettings:
. Set your object’sviewSizeHandler
to theviewSizeHandler
in therendererSettings
parameter. Extract any custom settings properties from yourrendererSettings
here or simply keep a reference to the renderer settings in your class if you need them to render your ad view. -
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. -
Create a subclass of
MPNativeCustomEvent
. -
Override the
requestAdWithAdapterInfo:
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 adapter Class Data. It should include any necessary information for requesting an ad on your network such as ad unit ID. -
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 anMPNativeAd
with theinitWithAdAdapter:
initializer. -
Before calling
customNativeEvent:didLoadAd:
on the adapter’s delegate, call the superclass’sprecacheImagesWithURLs: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 theMPNativeAd
object. -
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 Adapters
In the inline and fullscreen adapter subclasses, the methods called to load an ad include an NSDictionary
parameter (called info
) that you may use to provide your adapter 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 “adapter 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
Inline and Fullscreen Ads
The MoPub SDK will automatically record impressions and clicks for adapters in response to certain delegate callbacks.
For inline adapters, impressions are recorded on inlineAdAdapter:self didLoadAdWithAdView
, and clicks are recorded on inlineAdAdapterWillBeginUserAction:self
or inlineAdAdapterWillLeaveApplication:self
.
For fullscreen adapters, impressions are recorded on fullscreenAdAdapterAdDidAppear:self
, and clicks are recorded on fullscreenAdAdapterDidReceiveTap:self
.
If you require more control over when impressions and clicks are recorded, you may override the default behavior in your adapters by overriding enableAutomaticImpressionAndClickTracking
and returning NO
. You can then manually report impressions and clicks by calling fullscreenAdAdapterDidTrackImpression:self
and fullscreenAdAdapterDidTrackClick:self
on the adapter 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 March 30, 2021
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.
© 2021 MoPub (a division of Twitter, Inc.)