Renderización de anuncios de iPhone X

En esta guía, se muestran las prácticas recomendadas sobre cómo codificar tus apps para renderizar anuncios correctamente en el iPhone X.

Requisitos previos

  • Importa la versión 7.26.0 o una posterior del SDK de anuncios de Google para dispositivos móviles, ya sea solo o como parte de Firebase.

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

Creador de guiones gráficos y interfaces

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 una versión posterior) y tener como objetivo iOS 9 (o una versión posterior).

Abre tu archivo de Interface Builder y haz clic en la escena del controlador de vista. Verás las opciones del Documento del compilador de interfaces (Interface Builder Document) a la derecha. Consulta Usar las guías de diseño de área segura y asegúrate de compilar para iOS 9.0 y versiones posteriores como mínimo.

Te recomendamos que restrinjas el banner al tamaño requerido usando restricciones de ancho y alto.

Ahora puedes alinear el banner con la parte superior del área segura restringiendo la propiedad superior de GADBannerView a la parte superior del área segura:

De manera similar, puedes alinear el banner con la parte inferior del área segura restringiendo la propiedad inferior de GADBannerView a la parte inferior del área segura:

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

ViewController

Este es un fragmento de código del controlador de vista simple que hace el mínimo necesario para mostrar un banner en un GADBannerView como se configuró en el guion gráfico anterior:

Swift

class ViewController: UIViewController {

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

  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(GADRequest())
  }

}

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];
}

Alineación de los banners en el borde del área segura

Si deseas tener un banner alineado a la izquierda o 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 Usar guías de diseño de área segura, el compilador de interfaces 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 manera programática, puedes definir restricciones y posicionar el anuncio de banner en el código. En este ejemplo, se muestra cómo limitar un banner para que se centre horizontalmente en la parte inferior del área segura:

Swift

class ViewController: UIViewController {

  var bannerView: GADBannerView!

  override func viewDidLoad() {
    super.viewDidLoad()

    // Instantiate the banner view with your desired banner size.
    bannerView = GADBannerView(adSize: GADAdSizeBanner)
    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(GADRequest())
  }

  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 con facilidad para restringir la parte superior del área segura mediante la modificación de los atributos y las anclas que se usan.

Banners inteligentes

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

En el compilador de interfaces, esto se admite hasta iOS 9. Para ello, marca la opción Use Safe Area Layout Guides como se describió anteriormente.

En el código, debes hacer que tus restricciones perimetrales estén relacionadas con las guías de diseño del área segura cuando estén disponibles. Este es un fragmento de código que agrega una vista de banner a la vista y limita a la parte inferior de esta, de ancho completo:

Swift

func addBannerViewToView(_ bannerView: GADBannerView) {
  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 GADBannerView, deberás agregar restricciones a tu GADUnifiedNativeAdView (o la vista contenedora del anuncio) para respetar las guías de diseño de Área segura. Para las vistas nativas, te recomendamos que proporciones 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 es totalmente compatible con los formatos de anuncios intersticiales y recompensados para iPhone X.