Anuncio intersticial recompensado (beta)

Intersticial recompensado es 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, para 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
  • Valida las devoluciones de llamada de SSV (opcional)
  • Cómo registrarse para recibir devoluciones de llamada
  • Muestra el anuncio y administra el evento de recompensa

Carga un anuncio

La carga de un anuncio se realiza mediante la carga loadWithAdUnitID:request:completionHandler: en la Clase GADRewardedInterstitialAd. El método de carga requiere tu ID de unidad de anuncios, una GADRequest y un controlador de finalización a la que se llama cuando la carga de anuncios se realiza correctamente o falla. El tráfico cargado El objeto GADRewardedInterstitialAd se proporciona como parámetro en el recurso controlador. En el siguiente ejemplo, se muestra cómo cargar una 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;
        }
      }
  ];
}

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

Aplicaciones que requieren datos adicionales en el servidor de verificación deben usar el función de datos personalizados de los anuncios recompensados. Cualquier valor de cadena establecido en un anuncio recompensado el objeto se pasa al parámetro de consulta custom_data de la devolución de llamada de SSV. Si la respuesta es no se configura un valor de datos personalizado, el valor del parámetro de consulta custom_data no será 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 anuncio recompensado objeto de anuncio intersticial 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 recibir devoluciones de llamada

Para recibir notificaciones sobre eventos de presentación, debes implementar el protocolo GADFullScreenContentDelegate y asígnalo al La propiedad fullScreenContentDelegate del anuncio que se muestra. El El protocolo GADFullScreenContentDelegate controla las devoluciones de llamada cuando se muestra el anuncio. presenta con éxito o sin éxito, y cuando se descarta. Lo siguiente código 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 administra el evento de recompensa

Cuando presentes tu anuncio, debes proporcionar un objeto GADUserDidEarnRewardHandler para procesar la recompensa para el usuario.

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

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

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