Renderización de anuncios en el iPhone X

En esta guía, se demuestran las prácticas recomendadas para codificar tus apps de modo que rendericen anuncios correctamente en el iPhone X.

Requisitos previos

Los anuncios de banner deben colocarse en el "área segura" para evitar que queden ocultos por las esquinas redondeadas, la carcasa del sensor y el indicador de inicio. En esta página, encontrarás ejemplos de cómo agregar restricciones para colocar un banner en la parte superior o inferior del área segura.

Storyboard/Interface Builder

Si tu app usa Interface Builder, primero asegúrate de haber habilitado las guías de diseño del área segura. Para ello, debes ejecutar Xcode 9 o versiones posteriores, y tu app debe estar orientada a iOS 9 o versiones posteriores.

Abre el archivo de Interface Builder y haz clic en la escena del controlador de vistas. Verás las opciones de Interface Builder Document (Documento de Interface Builder) a la derecha. Marca la casilla de verificación Use Safe Area Layout Guides y asegúrate de que tu compilación sea para iOS 9.0 y versiones posteriores.

Te recomendamos que limites el banner al tamaño requerido con restricciones de ancho y altura.

Ahora puedes restringir la propiedad Top de GADBannerView a la parte superior del área segura para alinear el banner a esa sección:

De manera similar, puedes alinear el banner a la parte inferior del área segura si restringes la propiedad Bottom de GADBannerView a esa parte.

Tus restricciones ahora deberían verse similares a las de la siguiente captura de pantalla (el tamaño y la posición pueden variar):

ViewController

Este es un fragmento de código simple del controlador de vistas que hace lo mínimo necesario para mostrar un banner en una clase GADBannerView tal como se configuró en el storyboard anterior:

Swift

class ViewController: UIViewController {

  /// The banner view.
  @IBOutlet var bannerView: BannerView!

  override func viewDidLoad() {
    super.viewDidLoad()
    // Replace this ad unit ID with your own ad unit ID.
    bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
    bannerView.rootViewController = self
    bannerView.load(Request())
  }

}

Objective-C

@interface ViewController()

@property(nonatomic, strong) IBOutlet GADBannerView *bannerView;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  // Replace this ad unit ID with your own ad unit ID.
  self.bannerView.adUnitID = @"ca-app-pub-3940256099942544/2934735716";
  self.bannerView.rootViewController = self;
  GADRequest *request = [GADRequest request];
  [self.bannerView loadRequest:request];
}

Alinea los banners con el borde del área segura

Si deseas tener un banner alineado a la izquierda o a la derecha, restringe el borde izquierdo o derecho del banner al borde izquierdo o derecho del área segura, y no al borde izquierdo o derecho de la supervista.

Si tienes habilitada la opción Use Safe Area Layout Guides (Usar las guías de diseño de área segura), Interface Builder usará de forma predeterminada los bordes del área segura cuando agregues restricciones a la vista.

Programática

Si tu app crea anuncios de banner de forma programática, puedes definir restricciones y posicionar estos anuncios con el código que escribes. En este ejemplo, se muestra cómo restringir un banner para que se centre de forma horizontal en la parte inferior del área segura:

Swift

class ViewController: UIViewController {

  var bannerView: BannerView!

  override func viewDidLoad() {
    super.viewDidLoad()

    // Instantiate the banner view with your desired banner size.
    bannerView = BannerView(adSize: AdSizeBanner)
    addBannerViewToView(bannerView)
    bannerView.rootViewController = self
    // Set the ad unit ID to your own ad unit ID here.
    bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
    bannerView.load(Request())
  }

  func addBannerViewToView(_ bannerView: UIView) {
    bannerView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(bannerView)
    if #available(iOS 11.0, *) {
      positionBannerAtBottomOfSafeArea(bannerView)
    }
    else {
      positionBannerAtBottomOfView(bannerView)
    }
  }

  @available (iOS 11, *)
  func positionBannerAtBottomOfSafeArea(_ bannerView: UIView) {
    // Position the banner. Stick it to the bottom of the Safe Area.
    // Centered horizontally.
    let guide: UILayoutGuide = view.safeAreaLayoutGuide

    NSLayoutConstraint.activate(
      [bannerView.centerXAnchor.constraint(equalTo: guide.centerXAnchor),
       bannerView.bottomAnchor.constraint(equalTo: guide.bottomAnchor)]
    )
  }

  func positionBannerAtBottomOfView(_ bannerView: UIView) {
    // Center the banner horizontally.
    view.addConstraint(NSLayoutConstraint(item: bannerView,
                                          attribute: .centerX,
                                          relatedBy: .equal,
                                          toItem: view,
                                          attribute: .centerX,
                                          multiplier: 1,
                                          constant: 0))
    // Lock the banner to the top of the bottom layout guide.
    view.addConstraint(NSLayoutConstraint(item: bannerView,
                                          attribute: .bottom,
                                          relatedBy: .equal,
                                          toItem: self.bottomLayoutGuide,
                                          attribute: .top,
                                          multiplier: 1,
                                          constant: 0))
  }

}

Objective-C

@interface ViewController()

@property(nonatomic, strong) GADBannerView *bannerView;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  // Instantiate the banner view with your desired banner size.
  self.bannerView = [[GADBannerView alloc] initWithAdSize:GADAdSizeBanner];
  [self addBannerViewToView:self.bannerView];

  // Replace this ad unit ID with your own ad unit ID.
  self.bannerView.adUnitID = @"ca-app-pub-3940256099942544/2934735716";
  self.bannerView.rootViewController = self;
  GADRequest *request = [GADRequest request];
  [self.bannerView loadRequest:request];
}

#pragma mark - view positioning

-(void)addBannerViewToView:(UIView *_Nonnull)bannerView {
  self.bannerView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:self.bannerView];
  if (@available(ios 11.0, *)) {
    [self positionBannerViewAtBottomOfSafeArea:bannerView];
  } else {
    [self positionBannerViewAtBottomOfView:bannerView];
  }
}

- (void)positionBannerViewAtBottomOfSafeArea:(UIView *_Nonnull)bannerView NS_AVAILABLE_IOS(11.0) {
  // Position the banner. Stick it to the bottom of the Safe Area.
  // Centered horizontally.
  UILayoutGuide *guide = self.view.safeAreaLayoutGuide;
  [NSLayoutConstraint activateConstraints:@[
    [bannerView.centerXAnchor constraintEqualToAnchor:guide.centerXAnchor],
    [bannerView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor]
  ]];
}

- (void)positionBannerViewAtBottomOfView:(UIView *_Nonnull)bannerView {
  [self.view addConstraint:[NSLayoutConstraint constraintWithItem:bannerView
                                                        attribute:NSLayoutAttributeCenterX
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:self.view
                                                        attribute:NSLayoutAttributeCenterX
                                                       multiplier:1
                                                         constant:0]];
  [self.view addConstraint:[NSLayoutConstraint constraintWithItem:bannerView
                                                        attribute:NSLayoutAttributeBottom
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:self.bottomLayoutGuide
                                                        attribute:NSLayoutAttributeTop
                                                       multiplier:1
                                                         constant:0]];
}

@end

Las técnicas anteriores se pueden usar fácilmente para restringir la parte superior del área segura modificando los elementos fijos y los atributos usados.

Banners inteligentes

Si usas banners inteligentes, en especial en orientación horizontal, te recomendamos que uses restricciones para alinear los bordes del banner con los bordes izquierdo y derecho del área segura.

En Interface Builder, esta opción es compatible con iOS 9 y versiones posteriores si se marca la opción Use Safe Area Layout Guides como se describió anteriormente.

En el código, debes hacer que las restricciones de los bordes sean relativas a las guías de diseño de área segura cuando estén disponibles. A continuación, se incluye un fragmento de código que agrega una vista de banner a la vista y la restringe a la parte inferior de la vista, con ancho completo:

Swift

func addBannerViewToView(_ bannerView: BannerView) {
  bannerView.translatesAutoresizingMaskIntoConstraints = false
  view.addSubview(bannerView)
  if #available(iOS 11.0, *) {
    // In iOS 11, we need to constrain the view to the safe area.
    positionBannerViewFullWidthAtBottomOfSafeArea(bannerView)
  }
  else {
    // In lower iOS versions, safe area is not available so we use
    // bottom layout guide and view edges.
    positionBannerViewFullWidthAtBottomOfView(bannerView)
  }
}

// MARK: - view positioning
@available (iOS 11, *)
func positionBannerViewFullWidthAtBottomOfSafeArea(_ bannerView: UIView) {
  // Position the banner. Stick it to the bottom of the Safe Area.
  // Make it constrained to the edges of the safe area.
  let guide = view.safeAreaLayoutGuide
  NSLayoutConstraint.activate([
    guide.leftAnchor.constraint(equalTo: bannerView.leftAnchor),
    guide.rightAnchor.constraint(equalTo: bannerView.rightAnchor),
    guide.bottomAnchor.constraint(equalTo: bannerView.bottomAnchor)
  ])
}

func positionBannerViewFullWidthAtBottomOfView(_ bannerView: UIView) {
  view.addConstraint(NSLayoutConstraint(item: bannerView,
                                        attribute: .leading,
                                        relatedBy: .equal,
                                        toItem: view,
                                        attribute: .leading,
                                        multiplier: 1,
                                        constant: 0))
  view.addConstraint(NSLayoutConstraint(item: bannerView,
                                        attribute: .trailing,
                                        relatedBy: .equal,
                                        toItem: view,
                                        attribute: .trailing,
                                        multiplier: 1,
                                        constant: 0))
  view.addConstraint(NSLayoutConstraint(item: bannerView,
                                        attribute: .bottom,
                                        relatedBy: .equal,
                                        toItem: bottomLayoutGuide,
                                        attribute: .top,
                                        multiplier: 1,
                                        constant: 0))
}

Objective-C

- (void)addBannerViewToView:(UIView *)bannerView {
  bannerView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:bannerView];
  if (@available(ios 11.0, *)) {
    // In iOS 11, we need to constrain the view to the safe area.
    [self positionBannerViewFullWidthAtBottomOfSafeArea:bannerView];
  } else {
    // In lower iOS versions, safe area is not available so we use
    // bottom layout guide and view edges.
    [self positionBannerViewFullWidthAtBottomOfView:bannerView];
  }
}

#pragma mark - view positioning

- (void)positionBannerViewFullWidthAtBottomOfSafeArea:(UIView *_Nonnull)bannerView NS_AVAILABLE_IOS(11.0) {
  // Position the banner. Stick it to the bottom of the Safe Area.
  // Make it constrained to the edges of the safe area.
  UILayoutGuide *guide = self.view.safeAreaLayoutGuide;

  [NSLayoutConstraint activateConstraints:@[
    [guide.leftAnchor constraintEqualToAnchor:bannerView.leftAnchor],
    [guide.rightAnchor constraintEqualToAnchor:bannerView.rightAnchor],
    [guide.bottomAnchor constraintEqualToAnchor:bannerView.bottomAnchor]
  ]];
}

- (void)positionBannerViewFullWidthAtBottomOfView:(UIView *_Nonnull)bannerView {
  [self.view addConstraint:[NSLayoutConstraint constraintWithItem:bannerView
                                                        attribute:NSLayoutAttributeLeading
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:self.view
                                                        attribute:NSLayoutAttributeLeading
                                                       multiplier:1
                                                         constant:0]];
  [self.view addConstraint:[NSLayoutConstraint constraintWithItem:bannerView
                                                        attribute:NSLayoutAttributeTrailing
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:self.view
                                                        attribute:NSLayoutAttributeTrailing
                                                       multiplier:1
                                                         constant:0]];
  [self.view addConstraint:[NSLayoutConstraint constraintWithItem:bannerView
                                                        attribute:NSLayoutAttributeBottom
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:self.bottomLayoutGuide
                                                        attribute:NSLayoutAttributeTop
                                                       multiplier:1
                                                         constant:0]];
}

Anuncios nativos

Si tu app fija anuncios nativos en la parte superior o inferior de la pantalla, se aplican los mismos principios para los anuncios nativos que para los anuncios de banner. La diferencia clave es que, en lugar de agregar restricciones a una clase GADBannerView, deberás agregarlas a tu clase GADNativeAdView (o a la vista contenedora del anuncio) para respetar las guías de diseño de área segura. En el caso de las vistas nativas, recomendamos proporcionar restricciones de tamaño más explícitas.

Anuncios intersticiales y recompensados

A partir de la versión 7.26.0, el SDK de anuncios de Google para dispositivos móviles admite por completo los formatos de anuncios intersticiales y recompensados para iPhone X.