Anuncios en forma de banner

Los anuncios de banner son anuncios rectangulares que ocupan una parte del diseño de una aplicación. Ellas permanecerá en la pantalla mientras los usuarios interactúan con la aplicación, ya sea anclados en la en la parte superior o inferior de la pantalla, o bien intercalados con el contenido a medida que el usuario se desplaza. Los anuncios de banner se pueden actualizar automáticamente después de cierto tiempo. Consulta la Descripción general de los anuncios de banner. para obtener más información.

En esta guía, se explica cómo comenzar a usar los anuncios de banner adaptables fijos, que maximizan el rendimiento optimizando el tamaño del anuncio para cada dispositivo con un ancho de anuncio que especifiques.

Banner adaptable fijo

Los anuncios de banner adaptable fijos son anuncios con relación de aspecto fija, no normales anuncios de tamaño fijo. La relación de aspecto es similar al estándar de la industria de 320 × 50. Una vez especificas el ancho completo disponible, se mostrará un anuncio con una altura óptima para ese ancho. La altura óptima no cambia entre solicitudes del mismo dispositivo y las vistas circundantes no necesitan moverse cuando el anuncio se actualiza.

Requisitos previos

Probar siempre con anuncios de prueba

Cuando compiles y pruebes tus apps, asegúrate de usar anuncios de prueba en lugar de anuncios activos y en producción. De lo contrario, podría suspenderse tu cuenta.

La forma más sencilla de cargar anuncios de prueba es usar nuestro ID de unidad de anuncios de prueba exclusivo para iOS banners:

/21775744923/example/adaptive-banner

Se configuró de forma especial para mostrar anuncios de prueba para cada solicitud, y puedes usarlo en tus propias apps mientras codificas, pruebas y depuras. Solo haz asegúrate de reemplazarla con tu propio ID de unidad de anuncios antes de publicar tu app.

Para obtener más información sobre cómo funcionan los anuncios de prueba del SDK de anuncios para dispositivos móviles, consulta el artículo Anuncios.

Crea una GAMBannerView

Los anuncios de banner se muestran en GAMBannerView objetos, por lo que el primer paso para integrar anuncios de banner es incluir un GAMBannerView en tu jerarquía de vistas. Por lo general, esto se hace de manera programática o a través de Interface Builder.

De manera programática

También se puede crear una instancia de GAMBannerView directamente. En el siguiente ejemplo, se crea un GAMBannerView:

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController {

  var bannerView: GAMBannerView!

  override func viewDidLoad() {
    super.viewDidLoad()

    let viewWidth = view.frame.inset(by: view.safeAreaInsets).width

    // Here the current interface orientation is used. Use
    // GADLandscapeAnchoredAdaptiveBannerAdSizeWithWidth or
    // GADPortraitAnchoredAdaptiveBannerAdSizeWithWidth if you prefer to load an ad of a
    // particular orientation,
    let adaptiveSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)
    bannerView = GAMBannerView(adSize: adaptiveSize)

    addBannerViewToView(bannerView)
  }

  func addBannerViewToView(_ bannerView: GAMBannerView) {
    bannerView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(bannerView)
    // This example doesn't give width or height constraints, as the provided
    // ad size gives the banner an intrinsic content size to size the view.
    view.addConstraints(
      [NSLayoutConstraint(item: bannerView,
                          attribute: .bottom,
                          relatedBy: .equal,
                          toItem: view.safeAreaLayoutGuide,
                          attribute: .bottom,
                          multiplier: 1,
                          constant: 0),
      NSLayoutConstraint(item: bannerView,
                          attribute: .centerX,
                          relatedBy: .equal,
                          toItem: view,
                          attribute: .centerX,
                          multiplier: 1,
                          constant: 0)
      ])
  }
}

SwiftUI

Para usar un GAMBannerView, crea un UIViewRepresentable:

private struct BannerView: UIViewRepresentable {
  let adSize: GADAdSize

  init(_ adSize: GADAdSize) {
    self.adSize = adSize
  }

  func makeUIView(context: Context) -> UIView {
    // Wrap the GADBannerView in a UIView. GADBannerView automatically reloads a new ad when its
    // frame size changes; wrapping in a UIView container insulates the GADBannerView from size
    // changes that impact the view returned from makeUIView.
    let view = UIView()
    view.addSubview(context.coordinator.bannerView)
    return view
  }

  func updateUIView(_ uiView: UIView, context: Context) {
    context.coordinator.bannerView.adSize = adSize
  }

  func makeCoordinator() -> BannerCoordinator {
    return BannerCoordinator(self)
  }

Para administrar la inicialización y el comportamiento de GAMBannerView, crea un elemento Coordinator:

class BannerCoordinator: NSObject, GADBannerViewDelegate {

  private(set) lazy var bannerView: GADBannerView = {
    let banner = GADBannerView(adSize: parent.adSize)
    banner.adUnitID = "ca-app-pub-3940256099942544/2435281174"
    banner.load(GADRequest())
    banner.delegate = self
    return banner
  }()

  let parent: BannerView

  init(_ parent: BannerView) {
    self.parent = parent
  }

Para obtener el ancho de la vista, usa GeometryReader. Esta clase calcula el tamaño del anuncio adecuado para la orientación actual del dispositivo. El frame se establece en la altura calculada a partir del tamaño del anuncio.

var body: some View {
  GeometryReader { geometry in
    let adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(geometry.size.width)

    VStack {
      Spacer()
      BannerView(adSize)
        .frame(height: adSize.size.height)
    }
  }

Objective-C

Ten en cuenta que, en este caso, no brindamos restricciones de ancho ni altura, ya que proporcionado le dará al banner un tamaño de contenido intrínseco para ajustar el tamaño vista.

@import GoogleMobileAds;

@interface ViewController ()

@property(nonatomic, strong) GAMBannerView *bannerView;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  // Here safe area is taken into account, hence the view frame is used after the
  // view has been laid out.
  CGRect frame = UIEdgeInsetsInsetRect(self.view.frame, self.view.safeAreaInsets);
  CGFloat viewWidth = frame.size.width;

  // Here the current interface orientation is used. If the ad is being preloaded
  // for a future orientation change or different orientation, the function for the
  // relevant orientation should be used.
  GADAdSize adaptiveSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth);
  // In this case, we instantiate the banner with desired ad size.
  self.bannerView = [[GAMBannerView alloc] initWithAdSize:adaptiveSize];

  [self addBannerViewToView:self.bannerView];
}

- (void)addBannerViewToView:(UIView *)bannerView {
  bannerView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:bannerView];
  // This example doesn't give width or height constraints, as the provided
  // ad size gives the banner an intrinsic content size to size the view.
  [self.view addConstraints:@[
    [NSLayoutConstraint constraintWithItem:bannerView
                              attribute:NSLayoutAttributeBottom
                              relatedBy:NSLayoutRelationEqual
                                  toItem:self.view.safeAreaLayoutGuide
                              attribute:NSLayoutAttributeBottom
                              multiplier:1
                                constant:0],
    [NSLayoutConstraint constraintWithItem:bannerView
                              attribute:NSLayoutAttributeCenterX
                              relatedBy:NSLayoutRelationEqual
                                  toItem:self.view
                              attribute:NSLayoutAttributeCenterX
                              multiplier:1
                                constant:0]
                                ]];
}
@end

Creador de interfaces

Puedes agregar un GAMBannerView a un archivo de guion gráfico o xib. Cuando use asegúrate de solo agregar restricciones de posición al banner. Por ejemplo: cuando se muestre un banner adaptable en la parte inferior de la pantalla, configura la de la vista del banner igual a la parte superior de la Guía de diseño inferior y definir el centerX restricción igual al centerX de la supervisión.

El tamaño del anuncio del banner aún se establece de manera programática:

Swift

bannerView.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)

Objective-C

self.bannerView.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth);

Carga un anuncio

Una vez que se implemente el GAMBannerView y se configuren sus propiedades, será hora de cargar un anuncio. Para ello, se debe llamar a loadRequest: en un GAMRequest objeto:

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  // Set the ad unit ID and view controller that contains the GAMBannerView.
  bannerView.adUnitID = "/21775744923/example/adaptive-banner"
  bannerView.rootViewController = self

  bannerView.load(GAMRequest())
}

SwiftUI

banner.adUnitID = "ca-app-pub-3940256099942544/2435281174"
banner.load(GADRequest())

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];
  // Set the ad unit ID and view controller that contains the GAMBannerView.
  self.bannerView.adUnitID = @"/21775744923/example/adaptive-banner";
  self.bannerView.rootViewController = self;

  [self.bannerView loadRequest:[GAMRequest request]];
}

Los objetos GAMRequest representan una sola solicitud de anuncio y contienen propiedades para elementos como la información de segmentación.

Si tu anuncio no se carga, no necesitas solicitar otro explícitamente, ya que (siempre y cuando configures tu unidad de anuncios para que se actualice) SDK de anuncios de Google para dispositivos móviles respetará cualquier frecuencia de actualización que hayas especificado en el archivo de la IU de Google. Si no habilitaste la actualización, deberás enviar una nueva solicitud.

Eventos de anuncios

Mediante el uso de GADBannerViewDelegate, puedes escuchar eventos de ciclo de vida, como cuando se cierra un anuncio o el usuario sale de la aplicación.

Cómo registrarse para eventos de banners

Si deseas registrarte para eventos de anuncios de banner, establece la propiedad delegate en GAMBannerView a un objeto que implemente el Protocolo GADBannerViewDelegate. Por lo general, la clase que implementa banners Los anuncios también actúan como la clase delegada, en cuyo caso, la propiedad delegate puede establecerse en self.

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADBannerViewDelegate {

  var bannerView: GAMBannerView!

  override func viewDidLoad() {
    super.viewDidLoad()
    // ...
    bannerView.delegate = self
  }
}

SwiftUI

banner.delegate = self

Objective-C

@import GoogleMobileAds;

@interface ViewController () <GADBannerViewDelegate>

@property(nonatomic, strong) GAMBannerView *bannerView;

@end

@implementation ViewController

-   (void)viewDidLoad {
  [super viewDidLoad];
  // ...
  self.bannerView.delegate = self;
}

Implementa eventos de banner

Cada uno de los métodos de GADBannerViewDelegate se marca como opcional, por lo que solo necesitas implementar los métodos que deseas. En este ejemplo, se implementa cada método y registra un mensaje en la consola:

Swift

func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
  print("bannerViewDidReceiveAd")
}

func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
  print("bannerView:didFailToReceiveAdWithError: \(error.localizedDescription)")
}

func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
  print("bannerViewDidRecordImpression")
}

func bannerViewWillPresentScreen(_ bannerView: GADBannerView) {
  print("bannerViewWillPresentScreen")
}

func bannerViewWillDismissScreen(_ bannerView: GADBannerView) {
  print("bannerViewWillDIsmissScreen")
}

func bannerViewDidDismissScreen(_ bannerView: GADBannerView) {
  print("bannerViewDidDismissScreen")
}

Objective-C

- (void)bannerViewDidReceiveAd:(GADBannerView *)bannerView {
  NSLog(@"bannerViewDidReceiveAd");
}

- (void)bannerView:(GADBannerView *)bannerView didFailToReceiveAdWithError:(NSError *)error {
  NSLog(@"bannerView:didFailToReceiveAdWithError: %@", [error localizedDescription]);
}

- (void)bannerViewDidRecordImpression:(GADBannerView *)bannerView {
  NSLog(@"bannerViewDidRecordImpression");
}

- (void)bannerViewWillPresentScreen:(GADBannerView *)bannerView {
  NSLog(@"bannerViewWillPresentScreen");
}

- (void)bannerViewWillDismissScreen:(GADBannerView *)bannerView {
  NSLog(@"bannerViewWillDismissScreen");
}

- (void)bannerViewDidDismissScreen:(GADBannerView *)bannerView {
  NSLog(@"bannerViewDidDismissScreen");
}

Consulta el ejemplo de delegado de anuncios para hallar una implementación de métodos delegados de banners en la app de demostración de la API de iOS.

Swift Objective-C

Casos de uso

A continuación, se ofrecen algunos casos de uso de ejemplo para estos métodos de eventos de anuncios.

Cómo agregar un banner a la jerarquía de vista una vez que se recibe un anuncio

Te recomendamos que demores la adición de un GAMBannerView a la jerarquía de vista hasta que se reciba un anuncio. Para ello, escucha el evento bannerViewDidReceiveAd::

Swift

func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
  // Add banner to view and add constraints.
  addBannerViewToView(bannerView)
}

Objective-C

- (void)bannerViewDidReceiveAd:(GAMBannerView *)bannerView {
  // Add bannerView to view and add constraints as above.
  [self addBannerViewToView:self.bannerView];
}

Cómo animar un anuncio de banner

También puedes usar el evento bannerViewDidReceiveAd: para animar un anuncio banner una vez que se devuelve, como se muestra en el siguiente ejemplo:

Swift

func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
  bannerView.alpha = 0
  UIView.animate(withDuration: 1, animations: {
    bannerView.alpha = 1
  })
}

Objective-C

- (void)bannerViewDidReceiveAd:(GAMBannerView *)bannerView {
  bannerView.alpha = 0;
  [UIView animateWithDuration:1.0 animations:^{
    bannerView.alpha = 1;
  }];
}

Pausar y reanudar la app

El protocolo GADBannerViewDelegate tiene métodos para notificarte de eventos, como como cuando un clic hace que se presente o se descarte una superposición. Si quieres hacer un seguimiento de si estos eventos se debieron a anuncios, regístrate para estos GADBannerViewDelegate.

Para captar todos los tipos de presentaciones de diseños o invocaciones de navegadores externos, no solo las que se originan por clics de anuncios, es más conveniente para tu app la recepción de los métodos equivalentes en UIViewController o UIApplication. Esta es una tabla que muestra los métodos de iOS equivalentes que se invocan al mismo tiempo que Métodos GADBannerViewDelegate:

Método GADBannerViewDelegate Método de iOS
bannerViewWillPresentScreen: viewWillDisappear: de UIViewController
bannerViewWillDismissScreen: viewWillAppear: de UIViewController
bannerViewDidDismissScreen: viewDidAppear: de UIViewController

Recuento manual de impresiones

Puedes enviar pings de impresiones manualmente a Ad Manager si tienes solicitudes condiciones respecto de cuándo se debe registrar una impresión. Esto se puede hacer primero Habilita una GAMBannerView para las impresiones manuales antes de cargar un anuncio:

Swift

bannerView.enableManualImpressions = true

Objective-C

self.bannerView.enableManualImpressions = YES;

Cuando determinas que un anuncio se devolvió correctamente y está en pantalla puedes activar una impresión de forma manual:

Swift

bannerView.recordImpression()

Objective-C

[self.bannerView recordImpression];

Eventos de aplicaciones

Los eventos de aplicaciones le permiten crear anuncios que pueden enviar mensajes a su código de aplicación. El la app podrá realizar acciones en función de estos mensajes.

Puedes escuchar eventos de apps específicos de Ad Manager con GADAppEventDelegate. Estos eventos pueden ocurrir en cualquier momento del ciclo de vida del anuncio, incluso antes de que se llame a bannerViewDidReceiveAd: del objeto GADBannerViewDelegate.

Swift

// Implement your app event within this method. The delegate will be
// notified when the SDK receives an app event message from the ad.

// Called when the banner receives an app event.
optional public func bannerView(_ banner: GAMBannerView,
    didReceiveAppEvent name: String, withInfo info: String?)

Objective-C

// Implement your app event within this method. The delegate will be
// notified when the SDK receives an app event message from the ad.

@optional
// Called when the banner receives an app event.
-   (void)bannerView:(GAMBannerView *)banner
    didReceiveAppEvent:(NSString *)name
              withInfo:(NSString *)info;

Los métodos de eventos de tu app se pueden implementar en un controlador de vista:

Swift

import GoogleMobileAds

class ViewController: UIViewController, GADAppEventDelegate {}

Objective-C

@import GoogleMobileAds;

@interface ViewController : UIViewController <GADAppEventDelegate> {}

@end

Recuerda establecer el delegado con la propiedad appEventDelegate antes de realizar la solicitud de un anuncio.

Swift

bannerView.appEventDelegate = self

Objective-C

self.bannerView.appEventDelegate = self;

En este ejemplo, se muestra cómo cambiar el color de fondo de tu app Especifica el color mediante un evento de la app:

Swift

func bannerView(_ banner: GAMBannerView, didReceiveAppEvent name: String,
    withInfo info: String?) {
  if name == "color" {
    guard let info = info else { return }
    switch info {
    case "green":
      // Set background color to green.
      view.backgroundColor = UIColor.green
    case "blue":
      // Set background color to blue.
      view.backgroundColor = UIColor.blue
    default:
      // Set background color to black.
      view.backgroundColor = UIColor.black
    }
  }
}

Objective-C

- (void)bannerView:(GAMBannerView *)banner
    didReceiveAppEvent:(NSString *)name
              withInfo:(NSString *)info {
  if ([name isEqual:@"color"]) {
    if ([info isEqual:@"green"]) {
      // Set background color to green.
      self.view.backgroundColor = [UIColor greenColor];
    } else if ([info isEqual:@"blue"]) {
      // Set background color to blue.
      self.view.backgroundColor = [UIColor blueColor];
    } else {
      // Set background color to black.
      self.view.backgroundColor = [UIColor blackColor];
    }
  }
}

Y esta es la creatividad correspondiente que envía mensajes de eventos de la aplicación en color a appEventDelegate

<html>
<head>
  <script src="//www.gstatic.com/afma/api/v1/google_mobile_app_ads.js"></script>
  <script>
    document.addEventListener("DOMContentLoaded", function() {
      // Send a color=green event when ad loads.
      admob.events.dispatchAppEvent("color", "green");

      document.getElementById("ad").addEventListener("click", function() {
        // Send a color=blue event when ad is clicked.
        admob.events.dispatchAppEvent("color", "blue");
      });
    });
  </script>
  <style>
    #ad {
      width: 320px;
      height: 50px;
      top: 0px;
      left: 0px;
      font-size: 24pt;
      font-weight: bold;
      position: absolute;
      background: black;
      color: white;
      text-align: center;
    }
  </style>
</head>
<body>
  <div id="ad">Carpe diem!</div>
</body>
</html>

Consulta el ejemplo de eventos de aplicaciones de Ad Manager para ver una implementación de eventos de aplicaciones en la App de demostración de API de iOS.

Swift Objective-C

Recursos adicionales

Ejemplos en GitHub

Próximos pasos

Banners contraíbles

Los anuncios de banner contraíbles son anuncios de banner que inicialmente se presentan como un anuncio superpuesto, con un botón para contraer el anuncio a un tamaño más pequeño. Considera usarla para optimizar aún más el rendimiento. Consulta anuncios de banner plegables para obtener más información.

Banners adaptables intercalados

Los banners adaptables intercalados son banners más grandes y más altos en comparación con los banners adaptables fijos. banners. Tienen una altura variable y pueden ser tan altos como la pantalla del dispositivo. Se recomienda el uso de banners adaptables intercalados en lugar de anuncios de banner adaptable fijos Apps que colocan anuncios de banner en contenido por el que es posible desplazarse. Consulta el ajuste adaptable intercalado banners para obtener más información más detalles.

Explora otros temas