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, no se requiere que los usuarios habiliten la visualización de los anuncios intersticiales recompensados.
Requisitos previos
- Contar con el SDK de anuncios de Google para dispositivos móviles 7.60.0 o una versión posterior
- Completar la guía de introducción
Implementación
Los pasos principales para integrar los anuncios intersticiales recompensados son los siguientes:
- Cargar un anuncio
- [Opcional] Validar las devoluciones de llamada de SSV
- Regístrate para recibir devoluciones de llamada
- Mostrar el anuncio y controlar el evento de recompensa
Carga un anuncio
Para cargar un anuncio, puedes utilizar el método load(adUnitID:request)
en la clase GADRewardedInterstitialAd
.
Swift
import GoogleMobileAds
import UIKit
class ViewController: UIViewController {
private var rewardedInterstitialAd: RewardedInterstitialAd?
override func viewDidLoad() {
super.viewDidLoad()
Task {
do {
rewardedInterstitialAd = try await RewardedInterstitialAd.load(
with: "ca-app-pub-3940256099942544/6978759866", request: Request())
} catch {
print("Failed to load rewarded interstitial ad with error: \(error.localizedDescription)")
}
}
}
}
SwiftUI
import GoogleMobileAds
class RewardedInterstitialViewModel: NSObject, ObservableObject,
FullScreenContentDelegate
{
@Published var coins = 0
private var rewardedInterstitialAd: RewardedInterstitialAd?
func loadAd() async {
do {
rewardedInterstitialAd = try await RewardedInterstitialAd.load(
with: "ca-app-pub-3940256099942544/6978759866", request: Request())
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] Valida las devoluciones de llamada de la verificación del servidor (SSV)
Las apps que requieren datos adicionales en las devoluciones de llamada de la verificación del servidor deben usar la función de datos personalizados de los anuncios recompensados. Todos los valores de cadena establecidos en un objeto de anuncio recompensado se pasan al parámetro de consulta custom_data
de la devolución de llamada de la SSV. Si no se establece ningún valor de datos personalizados, el valor del parámetro de consulta custom_data
no estará presente en la devolución de llamada de la SSV.
La siguiente muestra de código indica cómo establecer datos personalizados en un objeto de anuncio intersticial recompensado antes de solicitar un anuncio.
Swift
do {
rewardedInterstitialAd = try await RewardedInterstitialAd.load(
withAdUnitID: "ca-app-pub-3940256099942544/6978759866", request: Request())
let options = ServerSideVerificationOptions()
options.customRewardText = "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;
}];
Regístrate para recibir devoluciones de llamada
Para recibir notificaciones de eventos de presentación, debes implementar el protocolo GADFullScreenContentDelegate
y asignarlo a la propiedad fullScreenContentDelegate
del anuncio devuelto. El protocolo GADFullScreenContentDelegate
controla las devoluciones de llamada para cuando el anuncio se presenta correctamente o con errores, y cuando se descarta. El siguiente código muestra cómo implementar el protocolo y asignarlo al anuncio:
Swift
import GoogleMobileAds
import UIKit
class ViewController: UIViewController, FullScreenContentDelegate {
private var rewardedInterstitialAd: RewardedInterstitialAd?
override func viewDidLoad() {
super.viewDidLoad()
Task {
do {
rewardedInterstitialAd = try await RewardedInterstitialAd.load(
with: "ca-app-pub-3940256099942544/6978759866", request: Request())
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: FullScreenPresentingAd, 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: FullScreenPresentingAd) {
print("Ad will present full screen content.")
}
/// Tells the delegate that the ad dismissed full screen content.
func adDidDismissFullScreenContent(_ ad: FullScreenPresentingAd) {
print("Ad did dismiss full screen content.")
}
}
SwiftUI
Asigna la propiedad fullScreenContentDelegate
al anuncio que se devolvió:
rewardedInterstitialAd?.fullScreenContentDelegate = self
Implementa el protocolo:
func adDidRecordImpression(_ ad: FullScreenPresentingAd) {
print("\(#function) called")
}
func adDidRecordClick(_ ad: FullScreenPresentingAd) {
print("\(#function) called")
}
func ad(
_ ad: FullScreenPresentingAd,
didFailToPresentFullScreenContentWithError error: Error
) {
print("\(#function) called")
}
func adWillPresentFullScreenContent(_ ad: FullScreenPresentingAd) {
print("\(#function) called")
}
func adWillDismissFullScreenContent(_ ad: FullScreenPresentingAd) {
print("\(#function) called")
}
func adDidDismissFullScreenContent(_ ad: FullScreenPresentingAd) {
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.");
}
Muestra el anuncio y controla el evento de recompensa
Cuando presentes tu anuncio, deberás proporcionar un objeto GADUserDidEarnRewardHandler
para controlar la recompensa destinada al 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(from: nil) {
let reward = rewardedInterstitialAd.adReward
print("Reward received with currency \(reward.amount), amount \(reward.amount.doubleValue)")
// TODO: Reward the user.
}
}
SwiftUI
Escucha los eventos de la IU en la vista para mostrar el anuncio.
var rewardedInterstitialBody: some View {
// ...
}
.onChange(
of: showAd,
perform: { newValue in
if newValue {
viewModel.showAd()
}
}
)
Presenta el anuncio intersticial recompensado desde el modelo de vista:
func showAd() {
guard let rewardedInterstitialAd = rewardedInterstitialAd else {
return print("Ad wasn't ready.")
}
rewardedInterstitialAd.present(from: 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.
}];
}
Ejemplos en GitHub
Consulta los ejemplos completos de anuncios intersticiales recompensados en tu idioma preferido:
Próximos pasos
Obtén más información sobre la privacidad del usuario.