Reklama pełnoekranowa z nagrodą

Wybierz platformę: Android iOS Unity Flutter

Reklama pełnoekranowa z nagrodą to format reklamy zachęcającej użytkownika do jej obejrzenia, który umożliwia oferowanie nagród za oglądanie reklam wyświetlających się automatycznie w naturalnych momentach przejściowych aplikacji. W przeciwieństwie do reklam z nagrodą użytkownicy nie muszą wyrazić zgody na wyświetlenie reklamy pełnoekranowej z nagrodą.

Wymagania wstępne

Implementacja

Główne etapy integracji reklam pełnoekranowych z nagrodą są następujące:

  • Wczytywanie reklamy
  • [Opcjonalnie] Weryfikowanie wywołań zwrotnych SSV
  • Rejestrowanie wywołań zwrotnych
  • Wyświetlanie reklamy i obsługa zdarzenia związanego z nagrodą

Wczytywanie reklamy

Reklamę można wczytać za pomocą metody load(adUnitID:request) w klasie GADRewardedInterstitialAd.

Swift

func loadAdManagerRewardedInterstitialAd() async {
  do {
    rewardedInterstitialAd = try await RewardedInterstitialAd.load(
      // Replace this ad unit ID with your own ad unit ID.
      with: "adUnitID", request: AdManagerRequest())
    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)loadAdManagerRewardedInterstitialAd {
  [GADRewardedInterstitialAd loadWithAdUnitID:"adUnitID"
                                      request:[GAMRequest 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;
                            }];
}

Zastąp adUnitID identyfikatorem jednostki reklamowej.

[Opcjonalnie] Weryfikowanie wywołań zwrotnych weryfikacji po stronie serwera

Aplikacje, które wymagają dodatkowych danych w wywołaniach zwrotnych weryfikacji po stronie serwera, powinny korzystać z funkcji danych niestandardowych w reklamach z nagrodą. Każda wartość ciągu znaków ustawiona w obiekcie reklamy z nagrodą jest przekazywana do parametru zapytania custom_data wywołania zwrotnego SSV. Jeśli nie ustawiono wartości danych niestandardowych, wartość parametru zapytania custom_data nie będzie obecna w wywołaniu zwrotnym SSV.

Poniższy przykładowy kod pokazuje, jak ustawić dane niestandardowe w obiekcie reklamy pełnoekranowej z nagrodą przed wysłaniem prośby o reklamę.

Swift

private func validateAdManagerServerSideVerification() async {
  do {
    rewardedInterstitialAd = try await RewardedInterstitialAd.load(
      // Replace this ad unit ID with your own ad unit ID.
      with: "adUnitID", request: AdManagerRequest())
    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)validateAdManagerServerSideVerification {
  // Replace this ad unit ID with your own ad unit ID.
  [GADRewardedInterstitialAd loadWithAdUnitID:"adUnitID"
                                      request:[GAMRequest 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;
                            }];
}

Zastąp SAMPLE_CUSTOM_DATA_STRING swoimi danymi niestandardowymi.

Rejestrowanie wywołań zwrotnych

Aby otrzymywać powiadomienia o wydarzeniach związanych z prezentacją, musisz przypisać wartość GADFullScreenContentDelegate do właściwości fullScreenContentDelegate zwróconej reklamy:

Swift

rewardedInterstitialAd?.fullScreenContentDelegate = self

SwiftUI

rewardedInterstitialAd?.fullScreenContentDelegate = self

Objective-C

self.rewardedInterstitialAd.fullScreenContentDelegate = self;

Protokół GADFullScreenContentDelegate obsługuje wywołania zwrotne w przypadku, gdy reklama zostanie wyświetlona lub nie, a także gdy zostanie zamknięta. Poniższy kod pokazuje, jak wdrożyć protokół i przypisać go do reklamy:

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

Wyświetlanie reklamy i obsługa zdarzenia związanego z nagrodą

Podczas wyświetlania reklamy musisz podać obiekt GADUserDidEarnRewardHandler, który będzie obsługiwać nagrodę dla użytkownika.

Poniższy kod przedstawia najlepszą metodę wyświetlania reklamy pełnoekranowej z nagrodą.

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

Odbieraj zdarzenia interfejsu w widoku, w którym ma się wyświetlać reklama.

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

Wyświetl reklamę pełnoekranową z nagrodą z modelu widoku:

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

Przykłady w GitHubie

Zobacz pełne przykłady reklam pełnoekranowych z nagrodą w wybranym języku:

Dalsze kroki

Dowiedz się więcej o prywatności użytkowników.