O intersticial premiado é um tipo de formato de anúncio incentivado que permite oferecer recompensas a anúncios exibidos automaticamente durante transições naturais do app. Ao contrário dos anúncios premiados, os usuários não precisam ativar a visualização dos intersticiais premiados.
Pré-requisitos
- SDK dos anúncios para dispositivos móveis do Google 7.60.0 ou superior.
- Concluir o Guia de primeiros passos.
Implementação
As principais etapas para integrar anúncios intersticiais premiados são as seguintes:
- Carregar um anúncio
- [Opcional] Validar callbacks de SSV
- Registrar para callbacks
- Exibir o anúncio e gerenciar o evento de recompensa
Carregar um anúncio
É possível carregar um anúncio usando o método estático loadWithAdUnitID:request:completionHandler:
na classe GADRewardedInterstitialAd
. O método de carregamento exige o ID do bloco de anúncios, um objeto GADRequest
e um gerenciador de conclusão que é chamado quando o carregamento do anúncio é concluído ou falha. O objeto GADRewardedInterstitialAd
carregado é fornecido como um parâmetro no gerenciador de conclusão. O exemplo abaixo mostra como carregar um GADRewardedInterstitialAd
na
classe ViewController
.
Swift
import GoogleMobileAds import UIKit class ViewController: UIViewController { private var rewardedInterstitialAd: GADRewardedInterstitialAd? override func viewDidLoad() { super.viewDidLoad() GADRewardedInterstitialAd.load(withAdUnitID:"ca-app-pub-3940256099942544/6978759866", request: GADRequest()) { ad, error in if let error = error { return print("Failed to load rewarded interstitial ad with error: \(error.localizedDescription)") } self.rewardedInterstitialAd = ad } } }
Objective-C
#import "ViewController.h" @interface ViewController () @property(nonatomic, strong) GADRewardedInterstitialAd* rewardedInterstitialAd; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [GADRewardedInterstitialAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/6978759866" request:[GADRequest request] completionHandler:^( GADRewardedInterstitialAd* _Nullable rewardedInterstitialAd, NSError* _Nullable error) { if (!error) { self.rewardedInterstitialAd = rewardedInterstitialAd; } } ]; }
[Opcional] Validar callbacks de verificação do servidor (SSV)
Apps que exigem dados extras nos callbacks de verificação do servidor precisam usar o recurso de dados personalizados dos anúncios premiados. Qualquer valor de string definido em um objeto de anúncio premiado é transmitido para o parâmetro de consulta custom_data
do callback da SSV. Se nenhum valor de dados personalizado for definido, o valor do parâmetro de consulta custom_data
não estará presente no callback da SSV.
O exemplo de código a seguir demonstra como definir dados personalizados em um objeto de anúncio intersticial premiado antes de solicitar um anúncio.
Swift
GADRewardedInterstitialAd.load(withAdUnitID:"ca-app-pub-3940256099942544/6978759866", request: request, completionHandler: { [self] ad, error in if let error != error { rewardedInterstitialAd = ad let options = GADServerSideVerificationOptions() options.customRewardString = "SAMPLE_CUSTOM_DATA_STRING" rewardedInterstitialAd.serverSideVerificationOptions = options }
Objective-C
GADRequest *request = [GADRequest request]; [GADRewardedInterstitialAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/6978759866" request:request 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 para callbacks
Para receber notificações sobre eventos de apresentação, implemente o protocolo GADFullScreenContentDelegate
e atribua-o à propriedade fullScreenContentDelegate
do anúncio retornado. O
protocolo GADFullScreenContentDelegate
processa callbacks para quando o anúncio
é exibido com sucesso ou não e quando ele é dispensado. O código a seguir mostra como implementar o protocolo e atribuí-lo ao anúncio:
Swift
class ViewController: UIViewController { private var rewardedInterstitialAd: GADRewardedInterstitialAd? override func viewDidLoad() { super.viewDidLoad() GADRewardedInterstitialAd.load(withAdUnitID:"ca-app-pub-3940256099942544/6978759866", request: GADRequest()) { ad, error in if let error = error { return print("Failed to load rewarded interstitial ad with error: \(error.localizedDescription)") } self.rewardedInterstitialAd = ad self.rewardedInterstitialAd?.fullScreenContentDelegate = self } } } extension ViewController: GADFullScreenContentDelegate { /// 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."); }
Exibir o anúncio e gerenciar o evento de recompensa
Ao apresentar o anúncio, é necessário fornecer um objeto GADUserDidEarnRewardHandler
para processar o prêmio para o usuário.
O código a seguir apresenta o melhor método para exibir um anúncio intersticial premiado.
Swift
func show() { guard let rewardedInterstitialAd = rewardedInterstitialAd else { return print("Ad wasn't ready.") } rewardedInterstitialAd.present(fromRootViewController: self) { let reward = rewardedInterstitialAd.adReward // TODO: Reward the user! } }
Objective-C
- (void)show { [_rewardedInterstitialAd presentFromRootViewController:self userDidEarnRewardHandler:^{ GADAdReward *reward = self.rewardedInterstitialAd.adReward; // TODO: Reward the user! }]; }
Próximas etapas
Saiba mais sobre a privacidade do usuário.