Nativo avanzado

Mostrar un formato del anuncio nativo definido por el sistema

Cuando se carga un anuncio nativo, tu app recibe un objeto de anuncio nativo mediante uno de los GADAdLoaderDelegate mensajes de protocolo. Luego, tu app será responsable de mostrar el anuncio (aunque no necesariamente tiene que hacerlo de inmediato). Para facilitar la visualización de formatos de anuncios definidos por el sistema, el SDK ofrece algunas sugerencias de Google Cloud.

GADNativeAdView

Para GADNativeAd, hay una "vista de anuncio" correspondiente clase: GADNativeAdView Esta clase de vista de anuncio es una UIView que los editores deberían usar para mostrar el anuncio. Un solo objeto GADNativeAdView, por ejemplo, puede mostrar una sola instancia de un elemento GADNativeAd. Cada uno de los objetos UIView que se usan para mostrar los Los recursos deben ser vistas secundarias de ese objeto GADNativeAdView.

Si mostraras un anuncio en una UITableView, por ejemplo, el la jerarquía de vista de una de las celdas podría verse de la siguiente manera:

La clase GADNativeAdView también proporciona el IBOutlets que se usa para registrar la vista utilizada para cada recurso individual y un método para registrar el GADNativeAd objeto en sí. Registrar las vistas de esta manera permite que el SDK realice las siguientes acciones automáticamente: gestionar tareas como:

  • Se registran los clics.
  • Se registran impresiones (cuando el primer píxel es visible en la pantalla).
  • Se muestra la superposición de AdChoices.

Superposición de AdChoices

Para anuncios nativos indirectos (se publican mediante Ad Manager) reabastecimiento o mediante Ad Exchange o AdSense), se agrega una superposición de AdChoices el SDK. Deja un espacio en la esquina de su vista de anuncios nativos para el logotipo de AdChoices insertado automáticamente. Además, asegúrate asegúrese de que la superposición de AdChoices esté ubicada en el contenido que permite que se muestre fácilmente visible. Para obtener más información sobre el aspecto y la función de la superposición, consulta la lineamientos de implementación de anuncios programáticos nativos

Atribución de anuncio para anuncios programáticos nativos

Cuando muestres anuncios programáticos nativos, debes mostrar una atribución de anuncio a significan que la vista es un anuncio. Consulta esta página para ver los lineamientos de políticas.

Ejemplo de código

Analicemos cómo mostrar anuncios nativos con las vistas que se cargan de forma dinámica a partir de archivos .xib. Este enfoque puede ser muy útil cuando se usa GADAdLoaders. configurada para solicitar múltiples formatos.

Cómo diseñar las UIViews

El primer paso es diseñar la UIViews que mostrará los recursos del anuncio nativo. Puedes hacerlo en Interface Builder como lo harías al crear cualquier otro .xib. A continuación, se muestra cómo usar el diseño anuncio podría verse:

Observa el valor Custom Class en la parte superior derecha de la imagen. Se establece en

GADNativeAdView Esta es la clase de vista de anuncio que se usa para mostrar un GADNativeAd.

También deberás configurar la clase personalizada para GADMediaView, que se usa. para mostrar el video o la imagen del anuncio.

Una vez que las vistas estén establecidas y hayas asignado la clase de vistas de anuncios correcta a del diseño, vincula las salidas de recursos de la vista de anuncio con el objeto UIViews que creaste. A continuación, se muestra cómo puedes vincular las salidas de recursos de la vista de anuncio al UIViews creado. para un anuncio:

En el panel de tomacorrientes, se vincularon los tomacorrientes de GADNativeAdView el UIViews establecido en Interface Builder. Esto permite el SDK sabe qué UIView muestra cada recurso. También es importante recordar que estas salidas representan las opiniones que son se puede hacer clic en el anuncio.

Mostrar el anuncio

Después de completar el diseño y de vincular las salidas, agrega el siguiente código a tu app que muestra un anuncio cuando se carga:

Swift

// Mark: - GADNativeAdLoaderDelegate
func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) {
  print("Received native ad: \(nativeAd)")
  refreshAdButton.isEnabled = true
  // Create and place ad in view hierarchy.
  let nibView = Bundle.main.loadNibNamed("NativeAdView", owner: nil, options: nil)?.first
  guard let nativeAdView = nibView as? GADNativeAdView else {
    return
  }
  setAdView(nativeAdView)

  // Set ourselves as the native ad delegate to be notified of native ad events.
  nativeAd.delegate = self

  // Populate the native ad view with the native ad assets.
  // The headline and mediaContent are guaranteed to be present in every native ad.
  (nativeAdView.headlineView as? UILabel)?.text = nativeAd.headline
  nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent

  // This app uses a fixed width for the GADMediaView and changes its height to match the aspect
  // ratio of the media it displays.
  if let mediaView = nativeAdView.mediaView, nativeAd.mediaContent.aspectRatio > 0 {
    let heightConstraint = NSLayoutConstraint(
      item: mediaView,
      attribute: .height,
      relatedBy: .equal,
      toItem: mediaView,
      attribute: .width,
      multiplier: CGFloat(1 / nativeAd.mediaContent.aspectRatio),
      constant: 0)
    heightConstraint.isActive = true
  }

  // These assets are not guaranteed to be present. Check that they are before
  // showing or hiding them.
  (nativeAdView.bodyView as? UILabel)?.text = nativeAd.body
  nativeAdView.bodyView?.isHidden = nativeAd.body == nil

  (nativeAdView.callToActionView as? UIButton)?.setTitle(nativeAd.callToAction, for: .normal)
  nativeAdView.callToActionView?.isHidden = nativeAd.callToAction == nil

  (nativeAdView.iconView as? UIImageView)?.image = nativeAd.icon?.image
  nativeAdView.iconView?.isHidden = nativeAd.icon == nil

  (nativeAdView.starRatingView as? UIImageView)?.image = imageOfStars(
    fromStarRating: nativeAd.starRating)
  nativeAdView.starRatingView?.isHidden = nativeAd.starRating == nil

  (nativeAdView.storeView as? UILabel)?.text = nativeAd.store
  nativeAdView.storeView?.isHidden = nativeAd.store == nil

  (nativeAdView.priceView as? UILabel)?.text = nativeAd.price
  nativeAdView.priceView?.isHidden = nativeAd.price == nil

  (nativeAdView.advertiserView as? UILabel)?.text = nativeAd.advertiser
  nativeAdView.advertiserView?.isHidden = nativeAd.advertiser == nil

  // For the SDK to process touch events properly, user interaction should be disabled.
  nativeAdView.callToActionView?.isUserInteractionEnabled = false

  // Associate the native ad view with the native ad object. This is
  // required to make the ad clickable.
  // Note: this should always be done after populating the ad views.
  nativeAdView.nativeAd = nativeAd
}

SwiftUI

Crea un modelo de vista

Crear un modelo de vista que cargue un anuncio nativo y publique sus datos cambios:

import GoogleMobileAds

class NativeAdViewModel: NSObject, ObservableObject, GADNativeAdLoaderDelegate {
  @Published var nativeAd: GADNativeAd?
  private var adLoader: GADAdLoader!

  func refreshAd() {
    adLoader = GADAdLoader(
      adUnitID: "ca-app-pub-3940256099942544/3986624511",
      // The UIViewController parameter is optional.
      rootViewController: nil,
      adTypes: [.native], options: nil)
    adLoader.delegate = self
    adLoader.load(GADRequest())
  }

  func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) {
    // Native ad data changes are published to its subscribers.
    self.nativeAd = nativeAd
    nativeAd.delegate = self
  }

  func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error) {
    print("\(adLoader) failed with error: \(error.localizedDescription)")
  }
}

Cómo crear un elemento UIViewRepresentable

Crea un UIViewRepresentable para GADNativeView y suscríbete a los cambios de datos en el ViewModel clase:

private struct NativeAdView: UIViewRepresentable {
  typealias UIViewType = GADNativeAdView

  // Observer to update the UIView when the native ad value changes.
  @ObservedObject var nativeViewModel: NativeAdViewModel

  func makeUIView(context: Context) -> GADNativeAdView {
    return
      Bundle.main.loadNibNamed(
        "NativeAdView",
        owner: nil,
        options: nil)?.first as! GADNativeAdView
  }

  func updateUIView(_ nativeAdView: GADNativeAdView, context: Context) {
    guard let nativeAd = nativeViewModel.nativeAd else { return }

    // Each UI property is configurable using your native ad.
    (nativeAdView.headlineView as? UILabel)?.text = nativeAd.headline

    nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent

    (nativeAdView.bodyView as? UILabel)?.text = nativeAd.body

    (nativeAdView.iconView as? UIImageView)?.image = nativeAd.icon?.image

    (nativeAdView.starRatingView as? UIImageView)?.image = imageOfStars(from: nativeAd.starRating)

    (nativeAdView.storeView as? UILabel)?.text = nativeAd.store

    (nativeAdView.priceView as? UILabel)?.text = nativeAd.price

    (nativeAdView.advertiserView as? UILabel)?.text = nativeAd.advertiser

    (nativeAdView.callToActionView as? UIButton)?.setTitle(nativeAd.callToAction, for: .normal)

    // For the SDK to process touch events properly, user interaction should be disabled.
    nativeAdView.callToActionView?.isUserInteractionEnabled = false

    // Associate the native ad view with the native ad object. This is required to make the ad
    // clickable.
    // Note: this should always be done after populating the ad views.
    nativeAdView.nativeAd = nativeAd
  }

Cómo agregar la vista a la jerarquía de vistas

En el siguiente código, se muestra cómo agregar UIViewRepresentable a la vista jerarquía:

struct NativeContentView: View {
  // Single source of truth for the native ad data.
  @StateObject private var nativeViewModel = NativeAdViewModel()

  var body: some View {
    ScrollView {
      VStack(spacing: 20) {
        NativeAdView(nativeViewModel: nativeViewModel)  // Updates when the native ad data changes.
          .frame(minHeight: 300)  // minHeight determined from xib.

Objective-C

#pragma mark GADNativeAdLoaderDelegate implementation

- (void)adLoader:(GADAdLoader *)adLoader didReceiveNativeAd:(GADNativeAd *)nativeAd {
  NSLog(@"Received native ad: %@", nativeAd);
  self.refreshButton.enabled = YES;

  // Create and place ad in view hierarchy.
  GADNativeAdView *nativeAdView =
      [[NSBundle mainBundle] loadNibNamed:@"NativeAdView" owner:nil options:nil].firstObject;
  [self setAdView:nativeAdView];

  // Set the mediaContent on the GADMediaView to populate it with available
  // video/image asset.
  nativeAdView.mediaView.mediaContent = nativeAd.mediaContent;

  // Populate the native ad view with the native ad assets.
  // The headline is guaranteed to be present in every native ad.
  ((UILabel *)nativeAdView.headlineView).text = nativeAd.headline;

  // These assets are not guaranteed to be present. Check that they are before
  // showing or hiding them.
  ((UILabel *)nativeAdView.bodyView).text = nativeAd.body;
  nativeAdView.bodyView.hidden = nativeAd.body ? NO : YES;

  [((UIButton *)nativeAdView.callToActionView)setTitle:nativeAd.callToAction
                                                forState:UIControlStateNormal];
  nativeAdView.callToActionView.hidden = nativeAd.callToAction ? NO : YES;

    ((UIImageView *)nativeAdView.iconView).image = nativeAd.icon.image;
  nativeAdView.iconView.hidden = nativeAd.icon ? NO : YES;

  ((UIImageView *)nativeAdView.starRatingView).image = [self imageForStars:nativeAd.starRating];
  nativeAdView.starRatingView.hidden = nativeAd.starRating ? NO : YES;

  ((UILabel *)nativeAdView.storeView).text = nativeAd.store;
  nativeAdView.storeView.hidden = nativeAd.store ? NO : YES;

  ((UILabel *)nativeAdView.priceView).text = nativeAd.price;
  nativeAdView.priceView.hidden = nativeAd.price ? NO : YES;

  ((UILabel *)nativeAdView.advertiserView).text = nativeAd.advertiser;
  nativeAdView.advertiserView.hidden = nativeAd.advertiser ? NO : YES;

  // In order for the SDK to process touch events properly, user interaction
  // should be disabled.
  nativeAdView.callToActionView.userInteractionEnabled = NO;

  // Associate the native ad view with the native ad object. This is
  // required to make the ad clickable.
  nativeAdView.nativeAd = nativeAd;
}

Ejemplo completo en GitHub

Mira el ejemplo completo de integración de anuncios nativos en Swift, SwiftUI y Objective-C siguiendo el vínculo correspondiente de GitHub.

Ejemplo de renderización personalizada de Swift Ejemplo de anuncios nativos de SwiftUI Ejemplo de renderización personalizada de Objective-C

GADMediaView

Los recursos de imagen y video se muestran a los usuarios a través de GADMediaView Este es un UIView que se puede definir en un archivo .xib o construirse de forma dinámica. Debe ubicarse dentro de la jerarquía de vistas de un GADNativeAdView, como sucede con a ninguna otra vista de recursos.

Al igual que ocurre con todas las vistas de elementos, la vista de medios debe tener su contenido. se complete. Se establece con el mediaContent propiedad en GADMediaView. El Propiedad mediaContent de GADNativeAd tiene contenido multimedia que se puede pasar a una GADMediaView

Este es un fragmento de la Ejemplo de renderización personalizada (Swift | Objective‐C) que muestra cómo completar la GADMediaView con los recursos de anuncios nativos usando GADMediaContent de GADNativeAd:

Swift

nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent

Objective-C

nativeAdView.mediaView.mediaContent = nativeAd.mediaContent;

En el archivo del Creador de interfaces para la vista de anuncios nativos, asegúrate de haber la clase personalizada de vistas establecida en GADMediaView y la conectaste al Enchufe mediaView.

Cómo cambiar el modo de contenido de la imagen

La clase GADMediaView respeta el UIView. contentMode cuando se muestran imágenes. Si quieres cambiar la forma en que se ajusta la escala de una imagen GADMediaView y configura el valor UIViewContentMode en la propiedad contentMode de GADMediaView para lograrlo.

Por ejemplo, para completar el GADMediaView cuando se muestra una imagen (el anuncio no tiene video):

Swift

nativeAdView.mediaView?.contentMode = .aspectFill

Objective-C

nativeAdView.mediaView.contentMode = UIViewContentModeAspectFill;

GADMediaContent

La GADMediaContent contiene los datos relacionados con el contenido multimedia del anuncio nativo, que se que se muestra con la clase GADMediaView Cuando se configura en el GADMediaView Propiedad mediaContent:

  • Si hay un elemento de video disponible, este se almacena en búfer y comienza a reproducirse en GADMediaView Para saber si un activo de video está disponible, revisa hasVideoContent

  • Si el anuncio no contiene un recurso de video, se descarga el recurso mainImage. y, en su lugar, se coloca dentro de GADMediaView.

Próximos pasos

Obtenga más información sobre la privacidad del usuario.