Intersticial recompensado

Los anuncios intersticiales recompensados son un tipo de formato de anuncio incentivado que te permite ofrecer recompensas por los anuncios que aparecen automáticamente durante las transiciones naturales de la app. A diferencia de los anuncios recompensados, los usuarios no necesitan aceptar ver un anuncio intersticial recompensado.

Requisitos previos

  • SDK de anuncios de Google para dispositivos móviles versión 7.60.0 o posterior.
  • Completa la Guía de introducción.

Implementación

Los pasos principales para integrar anuncios intersticiales recompensados son los siguientes:

  • Carga un anuncio
  • [Opcional] Validar devoluciones de llamada de SSV
  • Cómo registrarse para usar las devoluciones de llamada
  • Muestra el anuncio y controla el evento de recompensa

Carga un anuncio

La carga de un anuncio se logra con el método estático loadWithAdUnitID:request:completionHandler: en la clase GADRewardedInterstitialAd. El método de carga requiere tu ID de unidad de anuncios, un objeto GADRequest y un controlador de finalización al que se llama cuando la carga de anuncios falla o se realiza correctamente. El objeto GADRewardedInterstitialAd cargado se proporciona como parámetro en el controlador de finalización. En el siguiente ejemplo, se muestra cómo cargar un GADRewardedInterstitialAd en tu clase ViewController.

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController {

  private var rewardedInterstitialAd: GADRewardedInterstitialAd?

  override func viewDidLoad() {
    super.viewDidLoad()

    do {
      rewardedInterstitialAd = try await GADRewardedInterstitialAd.load(
        withAdUnitID: "ca-app-pub-3940256099942544/6978759866", request: GADRequest())
    } catch {
      print("Failed to load rewarded interstitial ad with error: \(error.localizedDescription)")
    }
  }
}

Objective‑C

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic, strong) GADRewardedInterstitialAd* rewardedInterstitialAd;
@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  [GADRewardedInterstitialAd
      loadWithAdUnitID:@"<var label='the ad unit ID'>ca-app-pub-3940256099942544/6978759866</var>"
                request:[GADRequest request]
      completionHandler:^(
          GADRewardedInterstitialAd* _Nullable rewardedInterstitialAd,
          NSError* _Nullable error) {
        if (!error) {
          self.rewardedInterstitialAd = rewardedInterstitialAd;
        }
      }
  ];
}

[Opcional] Valida las devoluciones de llamada de la verificación del servidor (SSV)

Las apps que requieren datos adicionales en las devoluciones de llamada de verificación del servidor deben usar la función de datos personalizados de los anuncios recompensados. Cualquier valor de cadena establecido en un objeto de anuncio recompensado se pasa al parámetro de búsqueda custom_data de la devolución de llamada de SSV. Si no se establece ningún valor de datos personalizado, el valor del parámetro de consulta custom_data no estará presente en la devolución de llamada de SSV.

En la siguiente muestra de código, se indica cómo configurar datos personalizados en un objeto de anuncio intersticial recompensado antes de solicitar un anuncio.

Swift

do {
  rewardedInterstitialAd = try await GADRewardedInterstitialAd.load(
    withAdUnitID: "ca-app-pub-3940256099942544/6978759866", request: GADRequest())
  let options = GADServerSideVerificationOptions()
  options.customRewardString = "SAMPLE_CUSTOM_DATA_STRING"
  rewardedInterstitialAd.serverSideVerificationOptions = options
} catch {
  print("Rewarded ad failed to load with error: \(error.localizedDescription)")
}

Objective‑C

[GADRewardedInterstitialAd
    loadWithAdUnitID:@"ca-app-pub-3940256099942544/6978759866"
              request:GADRequest
    completionHandler:^(GADRewardedInterstitialAd *ad, NSError *error) {
      if (error) {
        // Handle Error
        return;
      }
      self.rewardedInterstitialAd = ad;
      GADServerSideVerificationOptions *options =
          [[GADServerSideVerificationOptions alloc] init];
      options.customRewardString = @"SAMPLE_CUSTOM_DATA_STRING";
      ad.serverSideVerificationOptions = options;
    }];

Cómo registrarse para usar las devoluciones de llamada

Para recibir notificaciones sobre eventos de presentación, debes implementar el protocolo GADFullScreenContentDelegate y asignarlo a la propiedad fullScreenContentDelegate del anuncio que se muestra. El protocolo GADFullScreenContentDelegate controla las devoluciones de llamada cuando el anuncio se presenta de manera correcta o incorrecta, y cuando se descarta. En el siguiente código, se muestra cómo implementar el protocolo y asignarlo al anuncio:

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADFullScreenContentDelegate {

  private var rewardedInterstitialAd: GADRewardedInterstitialAd?

  override func viewDidLoad() {
    super.viewDidLoad()

    do {
      rewardedInterstitialAd = try await GADRewardedInterstitialAd.load(
        withAdUnitID: "ca-app-pub-3940256099942544/6978759866", request: GADRequest())
      self.rewardedInterstitialAd?.fullScreenContentDelegate = self
    } catch {
      print("Failed to load rewarded interstitial ad with error: \(error.localizedDescription)")
    }
  }

  /// Tells the delegate that the ad failed to present full screen content.
  func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
    print("Ad did fail to present full screen content.")
  }

  /// Tells the delegate that the ad will present full screen content.
  func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
    print("Ad will present full screen content.")
  }

  /// Tells the delegate that the ad dismissed full screen content.
  func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
    print("Ad did dismiss full screen content.")
  }
}

Objective‑C

@interface ViewController () <GADFullScreenContentDelegate>
@property(nonatomic, strong) GADRewardedInterstitialAd *rewardedInterstitialAd;
@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view.

  [GADRewardedInterstitialAd
      loadWithAdUnitID:@"ca-app-pub-3940256099942544/6978759866"
                request:[GADRequest request]
      completionHandler:^(
          GADRewardedInterstitialAd *_Nullable rewardedInterstitialAd,
          NSError *_Nullable error) {
        if (!error) {
          self.rewardedInterstitialAd = rewardedInterstitialAd;
          self.rewardedInterstitialAd.fullScreenContentDelegate = self;
        }
      }];
}

/// Tells the delegate that the ad failed to present full screen content.
- (void)ad:(nonnull id<GADFullScreenPresentingAd>)ad
didFailToPresentFullScreenContentWithError:(nonnull NSError *)error {
    NSLog(@"Ad did fail to present full screen content.");
}

/// Tells the delegate that the ad will present full screen content.
- (void)adWillPresentFullScreenContent:(nonnull id<GADFullScreenPresentingAd>)ad {

    NSLog(@"Ad will present full screen content.");
}

/// Tells the delegate that the ad dismissed full screen content.
- (void)adDidDismissFullScreenContent:(nonnull id<GADFullScreenPresentingAd>)ad {
  NSLog(@"Ad did dismiss full screen content.");
}

Muestra el anuncio y controla el evento de recompensa

Cuando presentes tu anuncio, debes proporcionar un objeto GADUserDidEarnRewardHandler para administrar la recompensa del usuario.

El siguiente código presenta el mejor método para mostrar un anuncio intersticial recompensado.

Swift

func show() {
  guard let rewardedInterstitialAd = rewardedInterstitialAd else {
    return print("Ad wasn't ready.")
  }

  // The UIViewController parameter is an optional.
  rewardedInterstitialAd.present(fromRootViewController: nil) {
    let reward = rewardedInterstitialAd.adReward
    print("Reward received with currency \(reward.amount), amount \(reward.amount.doubleValue)")
    // TODO: Reward the user.
  }
}

Objective‑C

- (void)show {
  // The UIViewController parameter is nullable.
  [_rewardedInterstitialAd presentFromRootViewController:nil
                                userDidEarnRewardHandler:^{

                                  GADAdReward *reward =
                                      self.rewardedInterstitialAd.adReward;
                                  // TODO: Reward the user.
                                }];
}

Próximos pasos

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