Se actualizó este documento.
La traducción en español no está disponible todavía.
Actualización del documento en inglés: 29 jun. 2021
Actualización del documento en español: 6 jul. 2018

Add Banner and Medium Rectangle Ads to an iOS App

The Audience Network allows you to monetize your iOS apps with Facebook ads. This guide explains how to create an iOS app that shows banner and medium rectangle ads.

You can change placements in Monetization Manager to the Medium Rectangle format if these were previously configured as Banner for bidding. Similarly, for any new medium rectangle placements, navigate to the placement settings page in Monetization Manager and select Medium Rectangle (not Banner).

Placements will deliver as normal even if they are not changed to the medium rectangle format. However, to avoid confusion, we recommend that you change these placements to medium rectangle.

If you're interested in other kinds of ad units, see the list of available types.

Banner and Medium Rectangle Ad Steps

Let's implement the following banner ad placement.



Step 1: Load and Show The Ad View

Step 2: Verify Impression and Click Logging

Step 3: How to Debug When Ad Not Shown

Step 4: Test Ads Integration

Step 1: Load and Show The Ad View

Ensure you have completed the iOS Setup Guides guide before you proceed.

Asegúrate de seguir la norma de diseño para iOS al crear anuncios nativos y banners para ofrecer una experiencia de usuario óptima.

  1. 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 to adContainer.
  2. Now, in your View Controller header file (or Swift file, if you are a Swift user), import FBAudienceNetwork, declare conformance to the FBAdViewDelegate protocol, and add an instance variable for the ad unit
    import UIKit
    import FBAudienceNetwork
    
    class ViewController: UIViewController, FBAdViewDelegate {
    
      @IBOutlet private var adContainer: UIView!
    
      private var adView: FBAdView?
    }
    #import <UIKit/UIKit.h>
    @import FBAudienceNetwork;
    
    @interface ViewController : UIViewController <FBAdViewDelegate>
    
    @property (nonatomic, weak) IBOutlet UIView *adContainer;
    @property (nonatomic, strong) FBAdView *adView;
    
    @end

  3. Add the code below to viewDidLoad; Create a new instance of FBAdView and add it to the view. FBAdView is a subclass of UIView. You can add it to your view hierarchy just like any other view.
    override func viewDidLoad() {
      super.viewDidLoad()
    
      // Instantiate an AdView object.
      // NOTE: the placement ID will eventually identify this as your app, you can ignore 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).
      let adView = FBAdView(placementID: "YOUR_PLACEMENT_ID", adSize: kFBAdSizeHeight50Banner, rootViewController: self)
      adView.frame = CGRect(x: 0, y: 0, width: 320, height: 250)
      adView.delegate = self
      adView.loadAd()
      self.adView = adView
    }
    - (void)viewDidLoad
    {
      [super viewDidLoad];
      // Instantiate an AdView 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).
      self.adView = [[FBAdView alloc] initWithPlacementID:@"YOUR_PLACEMENT_ID" adSize:kFBAdSizeHeight50Banner rootViewController:self];
      self.adView.frame = CGRectMake(0, 0, 320, 250);
      self.adView.delegate = self;
      [self.adView loadAd];
    }
    To add a Medium Rectangle ad instead, you just need to provide kFBAdSizeHeight250Rectangle in the adSize parameter to FBAdView.

    Audience Network supports three ad sizes to be used in your FBAdView. A unit's width is flexible with a minimum of 320px, and only the height is defined.

    Ad Format AdSize Reference Size Recommendation

    Medium Rectangle

    kFBAdSizeHeight 250Rectangle

    300x250

    This format is highly recommended because it provides higher performance, higher quality, and more CPU efficient

    Standard Banner

    kFBAdSizeHeight 50Banner

    320x50

    This format is suited to phones but not recommended because of poor performance and quality

    Large Banner

    kFBAdSizeHeight 90Banner

    320x90

    This format is suited to tablets and larger devices but not recommended because of poor performance and quality

  4. Replace YOUR_PLACEMENT_ID with your own placement id string. If you don't have a placement id or don't know how to get one, refer to the Getting Started Guide. Choose your build target to be device and run the above code, you should see something like this:



Para ver los anuncios de prueba, cambia la configuración al modo de prueba al publicarlos en el simulador. Consulta Cómo usar el modo de prueba para obtener más información.

Step 2: Verify Impression and Click Logging

Optionally, you can add the following functions to handle the cases where the ad is closed or when the user clicks on it:

func adViewDidClick(_ adView: FBAdView) {
  print("Ad was clicked.")
}

func adViewDidFinishHandlingClick(_ adView: FBAdView) {
  print("Ad did finish click handling.")
}

func adViewWillLogImpression(_ adView: FBAdView) {
  print("Ad impression is being captured.")
}
- (void)adViewDidClick:(FBAdView *)adView
{
  NSLog(@"Ad was clicked.");
}

- (void)adViewDidFinishHandlingClick:(FBAdView *)adView
{
  NSLog(@"Ad did finish click handling.");
}

- (void)adViewWillLogImpression:(FBAdView *)adView
{
  NSLog(@"Ad impression is being captured.");
}

Step 3: How to Debug When Ad Not Shown

Add and implement the following two delegate functions in your View Controller to handle ad loading failures:

func adView(_ adView: FBAdView, didFailWithError error: Error) {
  print("Ad failed to load with error: \(error.localizedDescription)")
}

func adViewDidLoad(_ adView: FBAdView) {
  print("Ad was loaded and ready to be displayed")
  showAd()
}

private func showAd() {
  guard let adView = adView, adView.isAdValid else {
    return
  }
  adContainer.addSubview(adView)
}
- (void)adView:(FBAdView *)adView didFailWithError:(NSError *)error
{
  NSLog(@"Ad failed to load with error: %@", error);
}

- (void)adViewDidLoad:(FBAdView *)adView
{
  NSLog(@"Ad was loaded and ready to be displayed");
  [self showAd];
}

- (void)showAd
{
  if (self.adView && self.adView.isAdValid) {
    [self.adContainer addSubview:self.adView];
  }
}

When there is no ad to show, the adView:didFailWithError: will be called with error.code set to 1001. If you use your own custom reporting or mediation layer, you may want to check the code value and detect this case. You can fallback to another ad network in this case, but do not re-request an ad immediately after.


Next Steps