Home
Unlabelled
Adding the Native Ad API in iOS
Adding the Native Ad API in iOS
The Native Ad API allows you to build a customized experience for the ads you show in your app. When using the Native Ad API, instead of receiving an ad ready to be displayed, you will receive a group of ad properties such as a title, an image, a call to action, and you will have to use them to construct a custom UIView where the ad is shown.
Please consult our native ads guide when designing native ads in your app.
Let's implement the following native ad placement. You will create the following views to our native ad.
View #1: advertiser iconView #2: ad titleView #3: sponsored labelView #4: advertiser choice | View #5: ad media viewView #6: social contextView #7: ad bodyView #8: ad call to action button |
Step 1: Create Native Ad Views in Storyboard
Step 2: Load and Show Native Ad
Step 3: How to Get Aspect Ratio of the Content and Apply Natural Width and Height
Step 4: Verify Impression and Click Logging
Step 5: How to Debug When Ad Not Shown
Step 6: Load Ad without Auto Cache
Step 7: Test Ads Integration
See Known Issues in the Change Log
Step 1: Create Native Ad Views in Storyboard
Ensure you have completed the Audience Network Getting Started and iOS Getting Started guides before you proceed.
When designing native ads and banner ads, ensure you have followed iOS layout guideline for optimal user experience.
- After you have created a new project from iOS Getting Started guides, open
Main.storyboard
. Add a UIView element to the main View element and name it toadUIView
. - In addition, add
adIconImageView
(FBAdIconView),adTitleLabel
(UILabel),adCoverMediaView
(FBMediaView),adSocialContext
(UILabel),adCallToActionButton
(UIButton),adOptionsView
(FBAdOptionsView),adBodyLabel
(UILabel),sponsoredLabel
(UILabel) underadUIView
as illustrated in the image below. - You may notice that there is a red arrow nearby View Controller Scene. This usually means that there are missing constraints in your layout.
You would need to select all the view objects in your scene and click the "resolve layout issue" icon to add missing constraints. - Now that you have created all the UI elements for showing a native ad, you will need to reference these UI elements in the ViewController interface. First open the
ViewController.m
, then dragadUIView
inside the ViewController interface object. You can name it asadUIView
. After, you will need to do the same thing foradIconImageView
,adTitleLabel
,adCoverMediaView
,adSocialContext
,adCallToActionButton
,adOptionsView
,adBodyLabel
,sponsoredLabel
. - Build and run the project. You should see from your device or simulator empty content as follows:
Now that you have created all the UI elements to show native ads, the next step is to load the native ad and bind the contents to the UI elements.
Step 2: Load and Show Native Ad
- Now, in your View Controller header file, import the SDK header, declare that ViewController implements the
FBNativeAdDelegate
protocol and add anativeAd
instance variable:#import <UIKit/UIKit.h> @import FBAudienceNetwork; @interface ViewController () <FBNativeAdDelegate> @property (strong, nonatomic) FBNativeAd *nativeAd; @end
- In
viewDidLoad
method, add the following lines of code to load native ad content.- (void)viewDidLoad { [super viewDidLoad]; // Instantiate a NativeAd object. // NOTE: the placement ID will eventually identify this as your App, you can ignore it for // now, while you are testing and replace it later when you have signed up. // While you are using this temporary code you will only get test ads and if you release // your code like this to the App Store your users will not receive ads (you will get a no fill error). FBNativeAd *nativeAd = [[FBNativeAd alloc] initWithPlacementID:@"YOUR_PLACEMENT_ID"]; nativeAd.delegate = self; [nativeAd loadAd]; }
ReplaceYOUR_PLACEMENT_ID
with your own placement id string. If you don't have a placement id or don't know how to get one, you can refer to the Getting Started Guide - The next step is to show ad when content is ready. You would need to implement
nativeAdDidLoad
method inViewController.m
file.- (void)nativeAdDidLoad:(FBNativeAd *)nativeAd { self.nativeAd = nativeAd; [self showNativeAd]; } - (void)showNativeAd { if (self.nativeAd && self.nativeAd.isAdValid) { [self.nativeAd unregisterView]; // Wire up UIView with the native ad; only call to action button and media view will be clickable. [self.nativeAd registerViewForInteraction:self.adUIView mediaView:self.adCoverMediaView iconView:self.adIconImageView viewController:self clickableViews:@[self.adCallToActionButton, self.adCoverMediaView]]; // Render native ads onto UIView self.adTitleLabel.text = self.nativeAd.advertiserName; self.adBodyLabel.text = self.nativeAd.bodyText; self.adSocialContextLabel.text = self.nativeAd.socialContext; self.sponsoredLabel.text = self.nativeAd.sponsoredTranslation; [self.adCallToActionButton setTitle:self.nativeAd.callToAction forState:UIControlStateNormal]; self.adOptionsView.nativeAd = self.nativeAd; } }
First, you will need to check if there is an existingnativeAd
object. If there is, you will need to callunregisterView
method. Then you will call[nativeAd registerViewForInteraction:viewController:mediaView:iconView:clickableViews:]
method.
WhatregisterViewForInteraction
mainly does is register what views will be tappable and what the delegate is to notify when a registered view is tapped. In this case,adCallToActionButton
andadCoverMediaView
will be tappable and when the view is tapped,ViewController
will be notified throughFBNativeAdDelegate
. - Choose your build target to be device and run the above code, you should see something like this:
Controlling Clickable Area
For a better user experience and better results, you should always consider controlling the clickable area of your ad to avoid unintentional clicks. Please refer to Audience Network SDK Policy page for more details about white space unclickable enforcement.
[nativeAd registerViewForInteraction:viewController:mediaView:iconView:clickableViews:]
method to register a list of views that can be clicked.
When running ads in the simulator, change the setting to test mode to view test ads. Please go to How to Use Test Mode for more information.
Step 3: How to Get the Aspect Ratio of the Content and Apply Natural Width and Height
In the example above, the media content of the ad is shown in
adCoverMediaView
and its object type is FBMediaView
. From previous step, we have shown how to use FBMediaView to load media content from a given FBNativeAd
object. This view takes the place of manually loading a cover image. When creating the FBMediaView
, its width and height can be either determined by the auto layout constraints set in the storyboard, or they can be hard-coded. However, the width and height of the view may not be fit with the actual cover image of the ad downloaded later. To fix this, the example following shows how to get the aspect ratio of the content and apply natural width and height:- In your View Controller header file, declare that ViewController implements the
FBMediaViewDelegate
protocol as follows:@interface ViewController : UIViewController <FBNativeAdDelegate, FBMediaViewDelegate>
- When the native ad is loaded, set the delegate of
FBMediaView
object to be the controller self as follows:- (void)nativeAdDidLoad:(FBNativeAd *)nativeAd { self.adCoverMediaView.delegate = self; }
- Implement
mediaViewDidLoad
method inViewController
as follows:- (void)mediaViewDidLoad:(FBMediaView *)mediaView { CGFloat currentAspect = mediaView.frame.size.width / mediaView.frame.size.height; NSLog(@"current aspect of media view: %f", currentAspect); CGFloat actualAspect = mediaView.aspectRatio; NSLog(@"actual aspect of media view: %f", actualAspect); }
mediaView.aspectRatio
returns a positive CGFloat, or 0.0 if no ad is currently loaded. Its value is valid after media view is loaded. There are convenience methods that will set the width and height of the FBMediaView object respecting its apsect ratio of the media content loaded. You can callapplyNaturalWidth
orapplyNaturalHeight
to update theFBMediaView
object's width or height to respect the media content's aspect ratio.
Step 4: Verify Impression and Click Logging
Optionally, you can add the following functions to handle the cases where the native ad is closed or when the user clicks on it:
- (void)nativeAdDidClick:(FBNativeAd *)nativeAd { NSLog(@"Native ad was clicked."); } - (void)nativeAdDidFinishHandlingClick:(FBNativeAd *)nativeAd { NSLog(@"Native ad did finish click handling."); } - (void)nativeAdWillLogImpression:(FBNativeAd *)nativeAd { NSLog(@"Native ad impression is being captured."); }
Step 5: How to Debug When Ad Not Shown
Add and implement the following function in your View Controller implementation file to handle ad loading failures and completions:
- (void)nativeAd:(FBNativeAd *)nativeAd didFailWithError:(NSError *)error { NSLog(@"Native ad failed to load with error: %@", error); }
Step 6: Load Ad without Auto Cache
- We strongly recommend to leave media caching on by default in all cases. However, we allow you to override the default. Please be very careful if you decide to override our default media caching.
@interface ViewController () <FBNativeAdDelegate, FBMediaViewDelegate> ... - (void)viewDidLoad { [super viewDidLoad]; // Instantiate a NativeAd object. // NOTE: the placement ID will eventually identify this as your App, you can ignore it for // now, while you are testing and replace it later when you have signed up. // While you are using this temporary code you will only get test ads and if you release // your code like this to the App Store your users will not receive ads (you will get a no fill error). FBNativeAd *nativeAd = [[FBNativeAd alloc] initWithPlacementID:@"YOUR_PLACEMENT_ID"]; nativeAd.delegate = self; [nativeAd loadAdWithMediaCachePolicy:FBNativeAdsCachePolicyNone]; }
- First, you will need to manually download all media for the native ad.
- (void)nativeAdDidLoad:(FBNativeAd *)nativeAd { self.adCoverMediaView.delegate = self; [nativeAd downloadMedia]; self.nativeAd = nativeAd; }
- Next, you should only call
registerViewForInteraction
and display ad aftermediaViewDidLoad
callback. All media has to be loaded and displayed for an eligible impression.- (void)mediaViewDidLoad:(FBMediaView *)mediaView { [self showNativeAd]; } - (void)showNativeAd { if (self.nativeAd && self.nativeAd.isAdValid) { [self.nativeAd unregisterView]; self.adCoverMediaView = mediaView; // Wire up UIView with the native ad; only call to action button and media view will be clickable. [self.nativeAd registerViewForInteraction:self.adUIView mediaView:self.adCoverMediaView iconView:self.adIconImageView viewController:self clickableViews:@[self.adCallToActionButton, self.adCoverMediaView]]; // Render native ads onto UIView self.adTitleLabel.text = self.nativeAd.advertiserName; self.adBodyLabel.text = self.nativeAd.bodyText; self.adSocialContextLabel.text = self.nativeAd.socialContext; self.sponsoredLabel.text = self.nativeAd.sponsoredTranslation; [self.adCallToActionButton setTitle:self.nativeAd.callToAction forState:UIControlStateNormal]; self.adOptions.nativeAd = self.nativeAd; } }
Next Steps
- Follow our guides for integrating different Ad Formats in your app:
- Native Ads
- Interstitial Ads
- Banners
- Test ads integration with your app
- Submit your app for review.
- As soon as we receive a request for an ad from your app or website, we'll review it to make sure it complies with Audience Network policies and the Facebook community standards. Learn more about our review process.
More Resources |
Getting Started Guide
Technical guide to get started with the Audience Network
Code Samples
Audience Network Ads Integration Samples
| FAQ
Audience Network FAQ
Native Ads Template
A more hands off approach when integrating Native Ads
|
Adding the Native Ad API in iOS
Reviewed by Code Labe
on
August 27, 2019
Rating: 5