Межстраничное объявление с вознаграждением

Выберите платформу: Android iOS Unity Flutter

Полосатая реклама с вознаграждением — это тип рекламы с вознаграждением, позволяющий предлагать вознаграждение за рекламу, которая автоматически появляется при естественном переходе между приложениями. В отличие от рекламы с вознаграждением, пользователям не требуется согласие на просмотр полноэкранной рекламы с вознаграждением.

Предпосылки

Выполнение

Основные шаги по интеграции вознагражденной межстраничной рекламы следующие:

  • Загрузить объявление
  • [Необязательно] Проверка обратных вызовов SSV
  • Зарегистрируйтесь для обратных звонков
  • Показ рекламы и обработка события вознаграждения

Загрузить объявление

Загрузка рекламы осуществляется с помощью метода load(adUnitID:request) класса GADRewardedInterstitialAd .

Быстрый

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

Замените adUnitID на идентификатор вашего рекламного блока.

[Необязательно] Проверка обратных вызовов проверки на стороне сервера (SSV)

Приложения, которым требуются дополнительные данные в обратных вызовах проверки на стороне сервера, должны использовать функцию пользовательских данных объявлений с вознаграждением. Любое строковое значение, заданное для объекта объявления с вознаграждением, передается в параметр запроса custom_data обратного вызова SSV. Если пользовательское значение данных не задано, значение параметра запроса custom_data не будет присутствовать в обратном вызове SSV.

В следующем примере кода показано, как задать пользовательские данные для объекта вознагражденной межстраничной рекламы перед запросом рекламы.

Быстрый

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

Замените SAMPLE_CUSTOM_DATA_STRING вашими пользовательскими данными.

Зарегистрируйтесь для обратных звонков

Чтобы получать уведомления о событиях презентации, необходимо назначить GADFullScreenContentDelegate свойству fullScreenContentDelegate возвращаемого объявления:

Быстрый

rewardedInterstitialAd?.fullScreenContentDelegate = self

SwiftUI

rewardedInterstitialAd?.fullScreenContentDelegate = self

Objective-C

self.rewardedInterstitialAd.fullScreenContentDelegate = self;

Протокол GADFullScreenContentDelegate обрабатывает обратные вызовы при успешном или неудачном показе рекламы, а также при её закрытии. Следующий код показывает, как реализовать протокол и назначить его рекламе:

Быстрый

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

Показ рекламы и обработка события вознаграждения

При показе рекламы необходимо предоставить объект GADUserDidEarnRewardHandler для обработки вознаграждения пользователя.

Следующий код демонстрирует наилучший метод отображения вознагражденной межстраничной рекламы.

Быстрый

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

Прослушивайте события пользовательского интерфейса в представлении для отображения рекламы.

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

Представьте вознагражденную рекламную вставку из модели представления:

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

Примеры на GitHub

Посмотрите полные примеры рекламных объявлений с вознаграждением на предпочитаемом вами языке:

Следующие шаги

Узнайте больше о конфиденциальности пользователей .