Anúncios intersticiais são anúncios em tela cheia que cobrem a interface de um aplicativo até fechadas pelo usuário. Normalmente, elas são exibidas em pontos de transição natural o fluxo de um aplicativo, como entre atividades ou durante a pausa entre fases de um jogo. Quando um app mostra um anúncio intersticial, o usuário tem a opção de escolher para tocar no anúncio e continuar até seu destino ou fechá-lo e voltar para o app. Estudo de caso.
Este guia mostra como integrar anúncios intersticiais em um app iOS.
Pré-requisitos
- SDK dos anúncios para dispositivos móveis do Google 8.0.0 ou mais recente.
- Leia o Guia explicativo.
Sempre faça testes com anúncios de teste
Ao criar e testar seus apps, use anúncios de teste em vez de anúncios de produção ativos. Sua conta poderá ser suspensa se isso não for feito.
A maneira mais fácil de carregar anúncios de teste é usar nosso ID de bloco de anúncios de teste dedicado
para intersticiais do iOS:
/21775744923/example/interstitial
Ele foi configurado especialmente para retornar anúncios de teste para cada solicitação, e você sem custos para usá-lo nos seus próprios apps durante a programação, o teste e a depuração. Apenas faça lembre-se de substituí-lo pelo seu próprio ID do bloco de anúncios antes de publicar o aplicativo.
Para mais informações sobre como funcionam os anúncios de teste do SDK dos anúncios para dispositivos móveis, consulte Anúncios de teste.
Implementação
As principais etapas para integrar anúncios intersticiais são:
- Carregue um anúncio.
- Registre-se para callbacks.
- Exiba o anúncio e processe o evento de recompensa.
Carregar um anúncio
É possível carregar um anúncio usando o
método load(adUnitID:request)
na
classe GAMInterstitialAd
.
Swift
import GoogleMobileAds
import UIKit
class ViewController: UIViewController {
private var interstitial: GAMInterstitialAd?
override func viewDidLoad() {
super.viewDidLoad()
Task {
do {
interstitial = try await GAMInterstitialAd.load(
withAdUnitID: "/21775744923/example/interstitial", request: GAMRequest())
} catch {
print("Failed to load interstitial ad with error: \(error.localizedDescription)")
}
}
}
}
SwiftUI
import GoogleMobileAds
class InterstitialViewModel: NSObject, GADFullScreenContentDelegate {
private var interstitialAd: GADInterstitialAd?
func loadAd() async {
do {
interstitialAd = try await GADInterstitialAd.load(
withAdUnitID: "ca-app-pub-3940256099942544/4411468910", request: GADRequest())
interstitialAd?.fullScreenContentDelegate = self
} catch {
print("Failed to load interstitial ad with error: \(error.localizedDescription)")
}
}
Objective-C
@import GoogleMobileAds;
@import UIKit;
@interface ViewController ()
@property(nonatomic, strong) GAMInterstitialAd *interstitial;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
GAMRequest *request = [GAMRequest request];
[GAMInterstitialAd loadWithAdManagerAdUnitID:@"/21775744923/example/interstitial"
request:request
completionHandler:^(GAMInterstitialAd *ad, NSError *error) {
if (error) {
NSLog(@"Failed to load interstitial ad with error: %@", [error localizedDescription]);
return;
}
self.interstitial = ad;
}];
}
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. A
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 interstitial: GAMInterstitialAd?
override func viewDidLoad() {
super.viewDidLoad()
Task {
do {
interstitial = try await GAMInterstitialAd.load(
withAdUnitID: "/21775744923/example/interstitial", request: GAMRequest())
interstitial?.fullScreenContentDelegate = self
} catch {
print("Failed to load 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:
interstitialAd?.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 interstitial ad.
interstitialAd = nil
}
Objective-C
@import GoogleMobileAds;
@import UIKit;
@interface ViewController () <GADFullScreenContentDelegate>
@property(nonatomic, strong) GAMInterstitialAd *interstitial;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
GAMRequest *request = [GAMRequest request];
[GAMInterstitialAd loadWithAdManagerAdUnitID:@"/21775744923/example/interstitial"
request:request
completionHandler:^(GAMInterstitialAd *ad, NSError *error) {
if (error) {
NSLog(@"Failed to load interstitial ad with error: %@", [error localizedDescription]);
return;
}
self.interstitial = ad;
self.interstitial.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.");
}
GAMInterstitialAd
é um objeto de uso único. Isso
significa que o anúncio intersticial não pode mais ser mostrado. Um(a) melhor
a prática é carregar outro anúncio intersticial
método adDidDismissFullScreenContent:
em GADFullScreenContentDelegate
, então
que o próximo anúncio intersticial comece a carregar assim que o anterior for
dispensada.
Exibir o anúncio
Os intersticiais devem ser exibidos durante pausas naturais no fluxo de um aplicativo. Entre os níveis de um jogo é um bom exemplo ou depois que o usuário conclui uma tarefa.
Swift
guard let interstitial = interstitial else {
return print("Ad wasn't ready.")
}
// The UIViewController parameter is an optional.
interstitial.present(fromRootViewController: nil)
SwiftUI
Ouça eventos de interface na visualização para determinar quando mostrar o anúncio.
var body: some View {
// ...
}
.onChange(of: countdownTimer.isComplete) { newValue in
showGameOverAlert = newValue
}
.alert(isPresented: $showGameOverAlert) {
Alert(
title: Text("Game Over"),
message: Text("You lasted \(countdownTimer.countdownTime) seconds"),
dismissButton: .cancel(
Text("OK"),
action: {
viewModel.showAd()
}))
Apresente o anúncio intersticial no modelo de visualização:
func showAd() {
guard let interstitialAd = interstitialAd else {
return print("Ad wasn't ready.")
}
interstitialAd.present(fromRootViewController: nil)
}
Objective-C
if (self.interstitial) {
// The UIViewController parameter is nullable.
[self.interstitial presentFromRootViewController:nil];
} else {
NSLog(@"Ad wasn't ready");
}
Práticas recomendadas
- Avalie se os anúncios intersticiais são o tipo certo de anúncio para seu app.
- Os anúncios intersticiais funcionam melhor em apps com pontos de transição natural. A conclusão de uma tarefa em um aplicativo, como compartilhar uma imagem ou concluir uma nível de jogo, cria esse ponto. Como o usuário está esperando uma pausa na para uma ação, é fácil apresentar um anúncio intersticial sem atrapalhar do usuário. Considere em quais pontos do fluxo de trabalho do app você exibir anúncios intersticiais e como o usuário provavelmente responderá.
- Lembre-se de pausar a ação ao exibir um anúncio intersticial.
- Há vários tipos diferentes de anúncios intersticiais: de texto, gráficos,
vídeo e muito mais. É importante garantir que, quando seu app exibir uma
intersticial, ela também suspende o uso de alguns recursos para permitir que o anúncio
aproveitá-las. Por exemplo, quando você faz a chamada para exibir um
anúncio intersticial, pause qualquer saída de áudio que esteja sendo produzida por seu aplicativo.
Você pode retomar a reprodução de sons no
adDidDismissFullScreenContent:
manipulador de eventos, que será invocado quando o usuário terminar de interagir com o anúncio. Além disso, considere interromper temporariamente qualquer computação intensa tarefas (como um loop de jogo) enquanto o anúncio está sendo exibido. Isso garantirá para que o usuário não veja gráficos lentos, sem resposta ou travamentos vídeo. - Permita um tempo de carregamento adequado.
- Tão importante quanto a exibição de anúncios intersticiais momento adequado, também é importante garantir que o usuário não precise aguarde até que eles sejam carregados. Carregar o anúncio com antecedência antes da exibição. pode garantir que seu app tenha um anúncio intersticial totalmente carregado quando chegou a hora de mostrar um.
- Não sobrecarregue o usuário com anúncios.
- Embora aumentar a frequência dos anúncios intersticiais no seu app possa parecer uma ótima maneira de aumentar a receita, também pode prejudicar a experiência do usuário e taxas de cliques mais baixas. Certifique-se de que os usuários não estejam interrompido e não poderá mais usar seu app.
- Não use o callback de conclusão de carregamento para mostrar o intersticial.
- Isso pode resultar em uma experiência ruim para o usuário. Em vez disso, pré-carregue o anúncio antes de
precisa mostrar. Em seguida, verifique o método
canPresentFromRootViewController:error:
. emGAMInterstitialAd
para descobrir se está pronto para ser mostrados.
Exemplos no GitHub
Confira os exemplos completos de anúncios intersticiais no idioma de sua preferência:
Próximas etapas
- Saiba mais sobre a segmentação de anúncios e diretrizes para anúncios intersticiais.
- Saiba mais sobre a privacidade do usuário.