Intersticial premiado (Beta)

O intersticial premiado é um tipo de formato de anúncio incentivado que permite oferecer recompensas para anúncios automaticamente durante as transições naturais do app. Diferente dos anúncios premiados, os usuários não precisam aceitar a visualização de um intersticial premiado.

Pré-requisitos

  • SDK dos anúncios para dispositivos móveis do Google 7.60.0 ou mais recente.
  • Leia o Guia explicativo.

Implementação

As principais etapas para integrar anúncios intersticiais premiados são:

  • Carregar um anúncio
  • [Opcional] Valide os callbacks de SSV
  • Registrar-se para callbacks
  • Exiba o anúncio e processe o evento de recompensa.

Carregar um anúncio

É possível carregar um anúncio usando a load(adUnitID:request). na classe GADRewardedInterstitialAd.

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController {

  private var rewardedInterstitialAd: GADRewardedInterstitialAd?

  override func viewDidLoad() {
    super.viewDidLoad()

    Task {
      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)")
      }
    }
  }
}

SwiftUI

import GoogleMobileAds

class RewardedInterstitialViewModel: NSObject, ObservableObject,
  GADFullScreenContentDelegate
{
  @Published var coins = 0
  private var rewardedInterstitialAd: GADRewardedInterstitialAd?

  func loadAd() async {
    do {
      rewardedInterstitialAd = try await GADRewardedInterstitialAd.load(
        withAdUnitID: "ca-app-pub-3940256099942544/6978759866", request: GADRequest())
      rewardedInterstitialAd?.fullScreenContentDelegate = self
    } 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] Validar os callbacks de verificação do lado do servidor (SSV)

Os apps que exigem dados extras em callbacks de verificação do servidor precisam usar o recurso de dados personalizados dos anúncios premiados. Qualquer valor de string definido em um anúncio premiado é transmitido ao parâmetro de consulta custom_data do callback SSV. Em caso negativo valor de dados personalizado estiver definido, o valor do parâmetro de consulta custom_data não será presentes no retorno de chamada de SSV.

O exemplo de código abaixo demonstra como definir dados personalizados em um objeto de anúncio intersticial premiado antes de solicitar um anúncio.

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

Registrar-se para callbacks

Para receber notificações de eventos de apresentação, você deve implementar o protocolo GADFullScreenContentDelegate e atribuí-lo à fullScreenContentDelegate do anúncio retornado. O o protocolo GADFullScreenContentDelegate processa callbacks para quando o anúncio apresenta com sucesso ou não e quando é dispensado. O seguinte mostra como implementar o protocolo e atribuí-lo ao anúncio:

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADFullScreenContentDelegate {

  private var rewardedInterstitialAd: GADRewardedInterstitialAd?

  override func viewDidLoad() {
    super.viewDidLoad()

    Task {
      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.")
  }
}

SwiftUI

Atribua a propriedade fullScreenContentDelegate ao anúncio retornado:

rewardedInterstitialAd?.fullScreenContentDelegate = self

Implemente o protocolo:

func adDidRecordImpression(_ ad: GADFullScreenPresentingAd) {
  print("\(#function) called")
}

func adDidRecordClick(_ ad: GADFullScreenPresentingAd) {
  print("\(#function) called")
}

func ad(
  _ ad: GADFullScreenPresentingAd,
  didFailToPresentFullScreenContentWithError error: Error
) {
  print("\(#function) called")
}

func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("\(#function) called")
}

func adWillDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("\(#function) called")
}

func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("\(#function) called")
  // Clear the rewarded interstitial ad.
  rewardedInterstitialAd = nil
}

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.");
}

Exiba o anúncio e processe o evento de recompensa.

Ao apresentar seu anúncio, forneça um objeto GADUserDidEarnRewardHandler para processar a recompensa do usuário.

O código a seguir apresenta o melhor método para mostrar um anúncio intersticial premiado.

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.
  }
}

SwiftUI

Ouça eventos de interface na visualização para exibir o anúncio.

var rewardedInterstitialBody: some View {
  // ...
  }
  .onChange(
    of: showAd,
    perform: { newValue in
      if newValue {
        viewModel.showAd()
      }
    }
  )

Apresente o anúncio intersticial premiado no modelo de visualização:

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

  rewardedInterstitialAd.present(fromRootViewController: nil) {
    let reward = rewardedInterstitialAd.adReward
    print("Reward amount: \(reward.amount)")
    self.addCoins(reward.amount.intValue)
  }
}

Objective-C

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

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

Exemplos no GitHub

Confira os exemplos completos de anúncios intersticiais premiados no seu idioma de preferência:

Próximas etapas

Saiba mais sobre a privacidade do usuário.