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. Banner los anuncios pueden actualizarse automáticamente después de un período determinado. Consulta la Descripción general de los anuncios de banner. para obtener más información.

En esta guía, se muestra cómo comenzar a usar las campañas anuncios de banner adaptable, lo que maximiza el rendimiento mediante la optimización del tamaño del anuncio para cada dispositivo mediante el ancho de anuncio que especifiques.

Banner adaptable fijo

Los anuncios de banner adaptable fijos son anuncios con relación de aspecto fija, no los anuncios 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, te mostrará un anuncio con una altura para ese ancho. La altura óptima no cambia entre las solicitudes de mismo dispositivo y no es necesario mover las vistas circundantes cuando el anuncio actualizaciones de software.

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: /6499/example/adaptive-banner

Se configuró de forma especial para mostrar anuncios de prueba para cada solicitud, y ahora usarla 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 de forma directa. Este es un ejemplo de cómo crear un GAMBannerView: alineado con la parte inferior central del área segura de la pantalla:

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

Objective-C

@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];
  [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

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.

Creador de interfaces

Se puede agregar una GAMBannerView a un guion gráfico o a un archivo .xib . Cuando uses este método, asegúrate de agregar solo restricciones de posición en el banner. Por ejemplo, cuando muestres un banner adaptable en la parte inferior de la pantalla, establece la parte inferior del banner igual a la parte superior de la parte inferior Guía de diseño y define la X central igual a la X central de la Superview.

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 GAMBannerView y sus propiedades estén implementados es momento 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 = "/6499/example/adaptive-banner"
  bannerView.rootViewController = self

  bannerView.load(GAMRequest())
}

Objective-C

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

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

Los objetos GAMRequest representan una única solicitud de anuncio. contienen propiedades, 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 los 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
  }
}

Objective-C

@import GoogleMobileAds;

@interface ViewController () <GADBannerViewDelegate>

@property(nonatomic, strong) GAMBannerView *bannerView;

@end

@implementation ViewController

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

Cómo implementar eventos de banners

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 ver una implementación de métodos delegados de banners en la aplicación iOS API Demo.

Swift Objective‐C

Casos de uso

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

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

Es posible que quieras retrasar la adición de un GAMBannerView a la jerarquía de vistas hasta que se recibe un anuncio. Para ello, escucha para el evento bannerViewDidReceiveAd::

Swift

func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
  // Add banner to view and add constraints as above.
  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. 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;
  }];
}

Cómo detener 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.

Captura todos los tipos de presentaciones superpuestas o invocaciones de navegadores externos, no solo aquellos que provienen de clics en los anuncios, es mejor que la aplicación escuche 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 la Se llama al 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

Pasos siguientes

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 el artículo sobre anuncios de banner contraíbles 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. Son de altura variable y pueden ser tan altas 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