O intersticial premiado é um tipo de formato de anúncio com incentivos que permite oferecer recompensas em anúncios que aparecem automaticamente durante transições naturais do app. Diferente dos anúncios premiados, os usuários não precisam ativar a visualização dos intersticiais premiados.
Pré-requisitos
- Leia o guia para iniciantes.
Implementação
Estas são as principais etapas para integrar anúncios intersticiais premiados:
- Carregar um anúncio
- [Opcional] Validar callbacks de SSV
- Registrar callbacks
- Exibir o anúncio e processar o evento de recompensa
Carregar um anúncio
Carregue um anúncio usando o método load(adUnitID:request)
na classe GADRewardedInterstitialAd
.
Swift
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
Substitua adUnitID pelo ID do seu bloco de anúncios.
[Opcional] Validar callbacks de verificação do lado do servidor (SSV)
Os apps que exigem dados extras em callbacks de verificação do lado do servidor (SSV, na sigla em inglês) precisam usar o recurso de dados personalizados dos anúncios premiados. Qualquer valor de string definido em um objeto
de anúncio premiado é transmitido ao parâmetro de consulta custom_data
do callback de SSV. Se nenhum
valor de dados personalizado for definido, o valor do parâmetro de consulta custom_data
não vai estar
presente no callback de 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
Objective-C
Substitua SAMPLE_CUSTOM_DATA_STRING pelos seus dados personalizados.
Registrar callbacks
Para receber notificações sobre eventos de apresentação, atribua
GADFullScreenContentDelegate
à propriedade fullScreenContentDelegate
do
anúncio retornado:
Swift
rewardedInterstitialAd?.fullScreenContentDelegate = self
SwiftUI
rewardedInterstitialAd?.fullScreenContentDelegate = self
Objective-C
self.rewardedInterstitialAd.fullScreenContentDelegate = self;
O protocolo GADFullScreenContentDelegate
processa callbacks quando o anúncio
é apresentado com ou sem sucesso e quando é dispensado. O código
a seguir mostra como implementar o protocolo e atribuí-lo ao anúncio:
Swift
func adDidRecordImpression(_ ad: FullScreenPresentingAd) {
print("\(#function) called.")
}
func adDidRecordClick(_ ad: FullScreenPresentingAd) {
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
}
func ad(
_ ad: FullScreenPresentingAd,
didFailToPresentFullScreenContentWithError error: Error
) {
print("\(#function) called with error: \(error.localizedDescription).")
}
SwiftUI
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
- (void)adDidRecordImpression:(id<GADFullScreenPresentingAd>)ad {
NSLog(@"%s called", __PRETTY_FUNCTION__);
}
- (void)adDidRecordClick:(id<GADFullScreenPresentingAd>)ad {
NSLog(@"%s called", __PRETTY_FUNCTION__);
}
- (void)adWillPresentFullScreenContent:(id<GADFullScreenPresentingAd>)ad {
NSLog(@"%s called", __PRETTY_FUNCTION__);
}
- (void)adWillDismissFullScreenContent:(id<GADFullScreenPresentingAd>)ad {
NSLog(@"%s called", __PRETTY_FUNCTION__);
}
- (void)adDidDismissFullScreenContent:(id<GADFullScreenPresentingAd>)ad {
NSLog(@"%s called", __PRETTY_FUNCTION__);
// Clear the rewarded interstitial ad.
self.rewardedInterstitialAd = nil;
}
- (void)ad:(id)ad didFailToPresentFullScreenContentWithError:(NSError *)error {
NSLog(@"%s called with error: %@", __PRETTY_FUNCTION__, error.localizedDescription);
}
Exibir o anúncio e processar o evento de recompensa
Ao apresentar seu anúncio, você precisa fornecer um objeto GADUserDidEarnRewardHandler
para processar a recompensa do usuário.
O código a seguir apresenta o melhor método para exibir um anúncio intersticial premiado.
Swift
func showRewardedInterstitialAd() {
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
Detecte eventos da interface na visualização para mostrar o anúncio.
var rewardedInterstitialBody: some View {
// ...
}
.onChange(
of: showAd,
perform: { newValue in
if newValue {
viewModel.showAd()
}
}
)
Apresente o anúncio intersticial premiado do modelo de visualização:
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)showRewardedInterstitialAd {
[self.rewardedInterstitialAd presentFromRootViewController:self
userDidEarnRewardHandler:^{
GADAdReward *reward = self.rewardedInterstitialAd.adReward;
NSString *rewardMessage = [NSString
stringWithFormat:@"Reward received with "
@"currency %@ , amount %ld",
reward.type, [reward.amount longValue]];
NSLog(@"%@", rewardMessage);
// TODO: Reward the user.
}];
}
Exemplos no GitHub
Confira exemplos completos de anúncios intersticiais premiados na sua linguagem preferida:
Próximas etapas
Saiba mais sobre a privacidade do usuário.