Interstitial con premio

Seleziona la piattaforma: Android iOS Unity Flutter

L'interstitial con premio è un tipo di formato dell'annuncio con incentivi che consente di offrire premi per gli annunci che vengono visualizzati automaticamente durante le normali transizioni dell'app. A differenza degli annunci con premio, gli utenti non sono tenuti ad attivare la visualizzazione di un annuncio interstitial con premio.

Prerequisiti

Implementazione

I passaggi principali per integrare gli annunci interstitial con premio sono i seguenti:

  • Caricare un annuncio
  • [Facoltativo] Convalida i callback SSV
  • Registrarsi per i callback
  • Mostra l'annuncio e gestisci l'evento con premio

Caricare un annuncio

Il caricamento di un annuncio viene eseguito utilizzando il metodo load(adUnitID:request) nella classe GADRewardedInterstitialAd.

Swift

func loadRewardedInterstitialAd() async {
  do {
    rewardedInterstitialAd = try await RewardedInterstitialAd.load(
      // Replace this ad unit ID with your own ad unit ID.
      with: "adUnitID", request: Request())
    rewardedInterstitialAd?.fullScreenContentDelegate = self
  } catch {
    print("Rewarded ad failed to load 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

- (void)loadRewardedInterstitialAd {
  [GADRewardedInterstitialAd loadWithAdUnitID:"adUnitID"
                                      request:[GADRequest request]
                            completionHandler:^(GADRewardedInterstitialAd *ad, NSError *error) {
                              if (error) {
                                NSLog(@"Failed to load rewarded interstitial ad with error: %@",
                                      error.localizedDescription);
                                return;
                              }
                              self.rewardedInterstitialAd = ad;
                              self.rewardedInterstitialAd.fullScreenContentDelegate = self;
                            }];
}

Sostituisci adUnitID con l'ID unità pubblicitaria.

[Facoltativo] Convalida i callback di verifica lato server (SSV)

Le app che richiedono dati aggiuntivi nei callback di verifica lato server devono utilizzare la funzionalità di dati personalizzati degli annunci con premio. Qualsiasi valore stringa impostato su un oggetto annuncio con premio viene passato al parametro di query custom_data del callback SSV. Se non è impostato alcun valore di dati personalizzati, il valore del parametro query custom_data non sarà presente nel callback SSV.

Il seguente esempio di codice mostra come impostare dati personalizzati su un oggetto annuncio interstiziale con premio prima di richiedere un annuncio.

Swift

private func validateServerSideVerification() async {
  do {
    rewardedInterstitialAd = try await RewardedInterstitialAd.load(
      // Replace this ad unit ID with your own ad unit ID.
      with: "adUnitID", 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

- (void)validateServerSideVerification {
  // Replace this ad unit ID with your own ad unit ID.
  [GADRewardedInterstitialAd loadWithAdUnitID:"adUnitID"
                                      request:[GADRequest request]
                            completionHandler:^(GADRewardedInterstitialAd *ad, NSError *error) {
                              if (error) {
                                NSLog(@"Rewarded interstitial ad failed to load with error: %@",
                                      error.localizedDescription);
                                return;
                              }
                              self.rewardedInterstitialAd = ad;
                              GADServerSideVerificationOptions *options =
                                  [[GADServerSideVerificationOptions alloc] init];
                              options.customRewardString = @""SAMPLE_CUSTOM_DATA_STRING"";
                              ad.serverSideVerificationOptions = options;
                            }];
}

Sostituisci SAMPLE_CUSTOM_DATA_STRING con i tuoi dati personalizzati.

Registrarsi per i callback

Per ricevere notifiche per gli eventi di presentazione, devi assegnare GADFullScreenContentDelegate alla proprietà fullScreenContentDelegate dell'annuncio restituito:

Swift

rewardedInterstitialAd?.fullScreenContentDelegate = self

SwiftUI

rewardedInterstitialAd?.fullScreenContentDelegate = self

Objective-C

self.rewardedInterstitialAd.fullScreenContentDelegate = self;

Il protocollo GADFullScreenContentDelegate gestisce i callback per quando l'annuncio viene visualizzato correttamente o meno e quando viene chiuso. Il seguente codice mostra come implementare il protocollo e assegnarlo all'annuncio:

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

Mostra l'annuncio e gestisci l'evento con premio

Quando presenti l'annuncio, devi fornire un oggetto GADUserDidEarnRewardHandler per gestire il premio per l'utente.

Il seguente codice presenta il metodo migliore per mostrare un annuncio interstiziale con premio.

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

Ascolta gli eventi della UI nella visualizzazione per mostrare l'annuncio.

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

Presenta l'annuncio interstitial con premio dal modello di visualizzazione:

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

Esempi su GitHub

Visualizza gli esempi completi di annunci interstitial con premio nella tua lingua preferita:

Passaggi successivi

Scopri di più sulla privacy degli utenti.