Миграция SDK

На этой странице описаны миграции для текущей и предыдущих версий.

Миграция с 10 на v11

Минимальная цель развертывания

Минимальная цель развертывания увеличена до iOS 12.

Минимальная версия Xcode

Минимальная поддерживаемая версия Xcode увеличена до 15.1.

Объявления перестают показываться на iOS 12

Google Mobile Ads SDK версии 11.0.0 показывает рекламу только на устройствах под управлением iOS 13 и более поздних версий.

Удалена зависимость GoogleAppMeasurement.

В версии 11.0.0 зависимость от GoogleAppMeasurement была удалена. Эта зависимость, которая обеспечивала переключение пользовательских показателей в AdMob, будет прекращена в начале 2024 года. Чтобы продолжить сбор пользовательских показателей в AdMob, свяжите свое приложение AdMob с Firebase и интегрируйте Google Analytics for Firebase SDK в свое приложение.

Изменения в полноэкранном представлении рекламы

Следующие изменения затрагивают различные форматы объявлений:

  • Приложение открыто
  • Межстраничный
  • Награжден
  • Межстраничное объявление с вознаграждением

Параметр контроллера представления в -canPresentFromRootViewController:error: и -presentFromRootViewController: имеет значение NULL. Если передано значение nil, реклама отображается из самого верхнего контроллера представления в иерархии контроллеров представлений.

Методы удалены

Следующие методы удалены.

v11.0.0 Тип Метод Примечания
GADAppOpenAd load(withAdUnitID adUnitID: String, request: GADRequest?, orientation: UIInterfaceOrientation) Вместо этого используйте load(withAdUnitID adUnitID: String, request: GADRequest?) .
GADMediationBannerAdEventDelegate willBackgroundApplication() Никакой замены.
GADMediationInterstitialAdEventDelegate willBackgroundApplication() Никакой замены.
GADMediationNativeAdEventDelegate willBackgroundApplication() Никакой замены.
GADMediationRewardedAdEventDelegate didRewardUser(with reward: GADAdReward) Вместо этого используйте didRewardUser() .
GADMediatedUnifiedNativeAdNotificationSource mediatedNativeAdWillLeaveApplication(_ mediatedNativeAd: GADMediatedUnifiedNativeAd) Никакой замены.
Конфигурация GADRequest setSameAppKeyEnabled(_ enabled: Bool) Вместо этого используйте setPublisherFirstPartyIDEnabled(_ enabled: Bool) .
tagForUnderAge(ofConsent underAgeOfConsent: Bool) Вместо этого используйте свойство tagForUnderAgeOfConsent .
tag(forChildDirectedTreatment childDirectedTreatment: Bool) Вместо этого используйте свойство tagForChildDirectedTreatment .

Свойства удалены

Следующие свойства удалены.

v11.0.0 Класс Свойство Примечания
GADMediationAdConfiguration имеетUserLocation Никакой замены.
пользовательШирота
пользовательДолгота
userLocationAccuracyInMeters
ребенокНаправленноеЛечение Вместо этого используйте GADMobileAds.sharedInstance.requestConfiguration.tagForChildDirectedTreatment .
GADResponseInfo имя_аднетворккласса Вместо этого используйте adNetworkClassName из loadedAdNetworkResponseInfo .

Удален GADAdFormatUnknown.

Удален GADAdFormatUnknown без замены.

Изменения в версии SDK для журналирования

Версия 11.0.0 удаляет sdkVersion . Чтобы зарегистрировать версию Google Mobile Ads SDK, используйте вместо этого versionNumber .

Версия 10.0.0

GADMobileAds.sharedInstance().sdkVersion

Версия 11.0.0

GADGetStringFromVersionNumber(GADMobileAds.sharedInstance().versionNumber)

Изменения в обработке ошибок GADAdLoader.

Начиная с версии 11.0.0, GADAdLoader не отправляет запрос объявления, если его delegate не соответствует протоколу делегирования запрошенных типов объявлений. Раньше это не удавалось после того, как был сделан запрос объявления.

Изменения в поведении тестирования

См. таблицу, в которой показаны обновленные условия, когда следующие свойства возвращают true .

Сорт Свойство
GADMediationAdConfiguration isTestRequest
GADCustomEventRequest isTesting
v10.0.0 v11.0.0
  • Устройство явно объявлено как тестовое в testDeviceIdentifiers .
  • Устройство явно объявлено как тестовое в testDeviceIdentifiers .
  • Устройство представляет собой симулятор.
  • Устройство явно объявлено как тестовое в пользовательском интерфейсе Ad Manager .

Миграция с версии 9 на версию 10

Объявления перестают показываться на iOS 11

Google Mobile Ads SDK версии 10.0.0 показывает рекламу только на устройствах под управлением iOS 12 и более поздних версий.

Обновление до Google Mobile Ads SDK версии 10.0.0 не приведет к поломке вашего приложения на устройствах iOS 11 и iOS 10, однако на этих устройствах реклама показываться не будет.

Требование идентификатора приложения Менеджера рекламы

Идентификатор приложения Менеджера рекламы теперь требуется в Info.plist для всех приложений Менеджера рекламы и требует наличия ca-app-pub-################~########## формат. Дополнительные сведения см. в разделе «Обновление Info.plist» .

Требование GoogleAppMeasurement.xcframework

GoogleAppMeasurement.xcframework теперь требуется для всех приложений Менеджера рекламы. Если вы устанавливаете Google Mobile Ads SDK через Cocoapods или Swift Package Manager , никаких дополнительных действий не требуется. Если вы устанавливаете платформы вручную, дополнительные сведения см. в разделе Загрузка вручную .

Сборка с использованием биткода больше не поддерживается.

Отключение биткода в мобильных приложениях теперь необходимо для интеграции Google Mobile Ads SDK.

Типы удалены

Тип Примечания
GADПол Никакой замены.
GADMRewardBasedVideoAdNetworkAdapterПротокол Все вознагражденные адаптеры-посредники, перечисленные в Choose Networks, прекратили использовать эти протоколы более года. Используйте GADMediationAdapter для медиации и пользовательских событий.
GADMRewardBasedVideoAdNetworkConnectorProtocol

Свойства удалены

Следующие свойства удаляются без замены.

v10.0.0 Класс Свойство
GADMediationAdRequest userДень рождения
пол пользователя
userHasLocation
пользовательШирота
пользовательДолгота
userLocationAccuracyInMeters
userLocationDescription
GADCustomEventRequest userHasLocation
пользовательШирота
пользовательДолгота
userLocationAccuracyInMeters
userLocationDescription
,

Объявления перестают показываться на iOS 11

Google Mobile Ads SDK версии 10.0.0 показывает рекламу только на устройствах под управлением iOS 12 и более поздних версий.

Обновление до Google Mobile Ads SDK версии 10.0.0 не приведет к поломке вашего приложения на устройствах iOS 11 и iOS 10, однако на этих устройствах реклама показываться не будет.

Требование идентификатора приложения Менеджера рекламы

Идентификатор приложения Менеджера рекламы теперь требуется в Info.plist для всех приложений Менеджера рекламы и требует наличия ca-app-pub-################~########## формат. Дополнительные сведения см. в разделе «Обновление Info.plist» .

Требование GoogleAppMeasurement.xcframework

GoogleAppMeasurement.xcframework теперь требуется для всех приложений Менеджера рекламы. Если вы устанавливаете Google Mobile Ads SDK через Cocoapods или Swift Package Manager , никаких дополнительных действий не требуется. Если вы устанавливаете платформы вручную, дополнительные сведения см. в разделе Загрузка вручную .

Сборка с использованием биткода больше не поддерживается.

Отключение биткода в мобильных приложениях теперь необходимо для интеграции Google Mobile Ads SDK.

Типы удалены

Тип Примечания
GADПол Никакой замены.
GADMRewardBasedVideoAdNetworkAdapterПротокол Все вознагражденные адаптеры-посредники, перечисленные в Choose Networks, прекратили использовать эти протоколы более года. Используйте GADMediationAdapter для медиации и пользовательских событий.
GADMRewardBasedVideoAdNetworkConnectorProtocol

Свойства удалены

Следующие свойства удаляются без замены.

v10.0.0 Класс Свойство
GADMediationAdRequest userДень рождения
пол пользователя
userHasLocation
пользовательШирота
пользовательДолгота
userLocationAccuracyInMeters
userLocationDescription
GADCustomEventRequest userHasLocation
пользовательШирота
пользовательДолгота
userLocationAccuracyInMeters
userLocationDescription

Миграция с версии 8 на версию 9

Объявления перестают показываться на iOS 10

Минимальная версия iOS, которую поддерживает Google Mobile Ads SDK версии 9.0.0, — iOS 11.

Обновление до Google Mobile Ads SDK версии 9.0.0 не приведет к поломке вашего приложения на устройствах iOS 10, однако реклама на этих устройствах показываться не будет.

Более строгое соблюдение элементов управления строкой состояния.

Начиная с версии 9.0.0, когда вы представляете полноэкранную рекламу, ваше приложение должно гарантировать, что реклама может управлять представлением строки состояния. Если вы этого не сделаете, вы увидите сообщение об ошибке в журналах.

В зависимости от конкретной компоновки контроллеров представления в вашем приложении вам, возможно, не потребуется вносить какие-либо изменения, чтобы обеспечить это. Подумайте, нужно ли вам установить свойство childViewControllerForStatusBarHidden в rootViewController вашего объявления.

Переименуйте adDidPresentFullScreenContent: в adWillPresentFullScreenContent:

Никаких изменений в поведении нет. Метод делегата вызывается непосредственно перед показом объявления, поэтому новое имя метода лучше отражает его функциональность.

Удалить API настройки местоположения в GADRequest

- (void)setLocationWithLatitude:longitude:accuracy: удален из GADRequest , поскольку данные о местоположении не используются Google для таргетинга рекламы. При необходимости используйте сторонние API для предоставления информации сторонним рекламным сетям.

Устаревание пользовательских интерфейсов событий

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

Все пользовательские протоколы событий устарели. Вместо этого используйте существующие протоколы GADMediationAdapter и GADMediationAdEventDelegate для достижения тех же функций. Это изменение повышает ясность и позволяет создавать собственные события для рекламы с вознаграждением и межпрокруточной рекламы, которые ранее были недоступны.

API

В таблице ниже перечислены соответствующие API-интерфейсы адаптера-посредника для API-интерфейсов пользовательских событий, которые следует использовать, начиная с версии 9.0.0.

v8 v9
GADCustomEventBanner
GADCustomEventМежстраничное объявление
GADCustomEventNativeAd
Адаптер GADMediation GADМедиацияБаннерРеклама
GADМедиацияМежстраничное объявление
GADМедиацияИнтерскроллерРеклама
GADМедиацияRewardedAd
GADMediationNativeAd
delegate Делегат возвращается обработчиком завершения загрузки каждой функции загрузки класса GADMediationAdapter .
-init -init
-requestBannerAd:parameter: label:request: -loadBannerForAdConfiguration: completionHandler:
-requestInterstitialAdWith Parameter:label:request: -loadInterstitialFor AdConfiguration: completionHandler:
-requestNativeAdWithParameter: request:adTypes:options: rootViewController: -loadNativeAdFor AdConfiguration: completionHandler:
Н/Д -loadInterscrollerAdFor AdConfiguration: completionHandler:
Н/Д -loadRewardedAdFor AdConfiguration: completionHandler:
-presentFromRootViewController: -presentFromViewController:
-handlesUserClicks -handlesUserClicks
-handlesUserImpressions -handlesUserImpressions

Делегировать методы

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

v8 v9
GADCustomEventBannerDelegate
GADCustomEventInterstitialDelegate
GADCustomEventNativeAdDelegate
GADMediationAdEventDelegate GADМедиацияОбъявление
-customEventBanner:didReceiveAd:
-customEventInterstitialDidReceiveAd:
Статус загрузки объявления включен в обработчик завершения загрузки каждой функции загрузки в классе GADMediationAdapter .
-customEventBanner:didFailAd:
-customEventInterstitial:didFailAd:
-customEventBannerWasClicked:
-customEventInterstitialWasClicked:
-reportClick
-customEventBannerWill PresentModal:
-customEventInterstitialWill PresentModal:
-willPresentFullScreenView
-customEventBannerWill DismissModal:
-customEventInterstitialWill DismissModal:
-willDismissFullScreenView
-customEventBannerDid DismissModal:
-customEventInterstitialDid DismissModal:
-didDismissFullScreenView
-customEventBannerWill LeaveApplication:
-customEventInterstitialWill LeaveApplication:
-willBackgroundApplication
viewControllerFor PresentingModalView -[GADMediationBannerAd view]

Другие удаленные/замененные методы и константы

Изменения метода, константы или свойства
kGAD- константы с префиксом Удаленный. Используйте константы с префиксом GAD- .
GADAdNetworkResponseInfo credentials были удалены. Вместо этого используйте adUnitMapping .
GAMRequest kGAMSimulatorID в GAMRequest устарел. Вместо этого используйте GADSimulatorID в GADRequestConfiguration .
GADCustomNativeAd mediaView в GADCustomNativeAd устарел. Вместо этого используйте mediaContent .
API для покупок в приложениях в GoogleMobileAds API inAppPurchase в GoogleMobileAds были удалены.

Миграция с версии 7 на версию 8

Google Mobile Ads SDK version 8.0.0 introduces a few major changes as well as some renames and removals of APIs.

Full-screen format API updates

Starting with version 8.0.0, interstitial and rewarded ads share a generic full screen ad style for more consistency. These new full-screen ad APIs have two major distinctions from the version 7 full-screen ad APIs:

  1. Static class method load.

    The previous approach to load/show a full-screen ad is as follows:

    1. Create an ad object instance and hold a reference to it.
    2. Assign a delegate that handles load and show callbacks.
    3. Load an ad.
    4. Check if ad is loaded using isReady.
    5. Show the ad.

    In version 8, the approach changes slightly. Load callbacks are no longer part of a delegate. Instead, they're passed into the load method as a completion handler:

    1. Call a static load method on the ad class and provide a load completion handler.
    2. In the load completion callback, keep a reference to the loaded ad that's returned.
    3. Assign a delegate that handles show callbacks.
    4. Show the ad.

    The new approach provides these benefits:

    • You won't ever have a reference to an ad that is not loaded.
    • You don't have to hold onto an ad object while it's loading.
  2. Consistent ad events.

    Event type Existing API v8 API
    Load events GADInterstitialDelegate or GADRewardedAdDelegate GAMInterstitialAdLoadCompletionHandler or GADRewardedAdLoadCompletionHandler
    Presentation events GADFullScreenContentDelegate

    Previously, to listen for any ad events, you would register a class that implements the GADInterstitialDelegate protocol to an interstitial's delegate property, or register a class that implements the GADRewardedAdDelegate protocol to a rewarded ad's delegate property depending on which format you're using. This same delegate had methods related to both the loading and presentation life cycle of an ad.

    With version 8, load and presentation events are separate. You can now register a GADFullScreenContentDelegate any time prior to showing an ad instead of being required to set a single delegate prior to loading the ad. Ad load events, which are specific to each format, move to a single load completion handler passed in the load method.

Interstitial

Load ad

The code snippets below show you how to load an interstitial ad and listen for events when the ad succeeds or fails to load.

v7

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADInterstitialDelegate {

  var interstitial: DFPInterstitial!

  override func viewDidLoad() {
    super.viewDidLoad()
    interstitial = DFPInterstitial(adUnitID: "/21775744923/example/interstitial")
    interstitial.delegate = self
    let request = GAMRequest()
    interstitial.load(request)
  }

  /// Tells the delegate an ad request succeeded.
  func interstitialDidReceiveAd(_ ad: DFPInterstitial) {
    print("Interstitial ad loaded.")
  }

  /// Tells the delegate an ad request failed.
  func interstitial(_ ad: DFPInterstitial, didFailToReceiveAdWithError error: GADRequestError) {
    print("Interstitial ad failed to load with error: \(error.localizedDescription)")
  }
}

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) DFPInterstitial *interstitial;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  self.interstitial = [[DFPInterstitial alloc]
      initWithAdUnitID:@"/21775744923/example/interstitial"];
  self.interstitial.delegate = self;
  GAMRequest *request = [GAMRequest request];
  [self.interstitial loadRequest:request];
}

/// Tells the delegate an ad request succeeded.
- (void)interstitialDidReceiveAd:(DFPInterstitial *)ad {
  NSLog(@"Insterstitial ad loaded.");
}

/// Tells the delegate an ad request failed.
- (void)interstitial:(DFPInterstitial *)ad
    didFailToReceiveAdWithError:(GADRequestError *)error {
  NSLog(@"Interstitial ad failed to load with error: %@", [error localizedDescription]);
}

v8

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADFullScreenContentDelegate {

  var interstitial: GAMInterstitialAd?

  override func viewDidLoad() {
    super.viewDidLoad()
    let request = GAMRequest()
    GAMInterstitialAd.load(withAdUnitID:"ca-app-pub-8123415297019784/4985798738",
                                request: request,
                      completionHandler: { (ad, error) in
                        if let error = error {
                          print("Failed to load interstitial ad with error: \(error.localizedDescription)")
                          return
                        }
                        self.interstitial = ad
                        self.interstitial.fullScreenContentDelegate = self
                      }
    )
  }
}

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 loadWithAdUnitID:@"/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;
  }];
}

Display ad

v7

Swift

func showInterstitial() {
  ...
  if interstitial.isReady {
    interstitial.present(fromRootViewController: self)
  } else {
    print("Ad wasn't ready")
  }
}

Objective-C

- (void)showInterstitial: {
  ...
  if (self.interstitial.isReady) {
    [self.interstitial presentFromRootViewController:self];
  } else {
    NSLog(@"Ad wasn't ready");
  }
}

v8

Swift

func showInterstitial() {
  ...
  if let ad = interstitial {
    ad.present(fromRootViewController: self)
  } else {
    print("Ad wasn't ready")
  }
}

Objective-C

- (void)showInterstitial: {
  ...
  if (self.interstitial) {
    [self.interstitial presentFromRootViewController:self];
  } else {
    NSLog(@"Ad wasn't ready");
  }
}

Presentation ad events

The code snippets below show you how to handle callbacks for when the ad presents (successfully or unsuccessfully) and when it is dismissed.

v7

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  interstitial = DFPInterstitial(adUnitID: "/21775744923/example/interstitial")
  interstitial.delegate = self
  ...
}

/// Tells the delegate that an interstitial will be presented.
func interstitialWillPresentScreen(_ ad: DFPInterstitial) {
  print("Interstitial ad will be presented.")
}

/// Tells the delegate the interstitial is to be animated off the screen.
func interstitialWillDismissScreen(_ ad: DFPInterstitial) {
  print("Interstitial ad will be dismissed.")
}

/// Tells the delegate the interstitial had been animated off the screen.
func interstitialDidDismissScreen(_ ad: DFPInterstitial) {
  print("Interstitial ad dismissed.")
}

/// Tells the delegate that a user click will open another app
/// (such as the App Store), backgrounding the current app.
///
/// This is not a reliable callback for an ad click event and is removed in
/// version 8. If you wish to listen to an ad causing a user to leave the app,
/// use applicationWillResignActive: or sceneWillResignActive: instead.
func interstitialWillLeaveApplication(_ ad: DFPInterstitial) {
  print("Interstitial ad will leave application.")
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];
  self.interstitial = [[DFPInterstitial alloc] initWithAdUnitID:"/21775744923/example/interstitial"];
  self.interstitial.delegate = self;
  ...
}

/// Tells the delegate that an interstitial will be presented.
- (void)interstitialWillPresentScreen:(DFPInterstitial *)ad {
  NSLog(@"Interstitial ad will be presented.");
}

/// Tells the delegate the interstitial is to be animated off the screen.
- (void)interstitialWillDismissScreen:(DFPInterstitial *)ad {
  NSLog(@"Interstitial ad will be dismissed.");
}

/// Tells the delegate the interstitial had been animated off the screen.
- (void)interstitialDidDismissScreen:(DFPInterstitial *)ad {
  NSLog(@"Interstitial ad dismissed.");
}

/// Tells the delegate that a user click will open another app
/// (such as the App Store), backgrounding the current app.
///
/// This is not a reliable callback for an ad click event and is removed in
/// version 8. If you wish to listen to an ad causing a user to leave the app,
/// use applicationWillResignActive: or sceneWillResignActive: instead.
- (void)interstitialWillLeaveApplication:(DFPInterstitial *)ad {
  NSLog(@"Interstitial ad will leave application.");
}

v8

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  let request = GAMRequest()
  GAMInterstitialAd.load(withAdUnitID:"ca-app-pub-8123415297019784/4985798738",
                              request: request,
                    completionHandler: { (ad, error) in
                      if let error = error {
                        print(error.localizedDescription)
                        return
                      }
                      self.interstitial = ad
                      self.interstitial.fullScreenContentDelegate = self
                    }
  )
}

func adDidPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("Ad did present full screen content.")
}

func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
  print("Ad failed to present full screen content with error \(error.localizedDescription).")
}

func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("Ad did dismiss full screen content.")
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];
  GAMRequest *request = [GAMRequest request];
  [GAMInterstitialAd loadWithAdUnitID:@"/21775744923/example/interstitial"
                              request:request
                    completionHandler:^(GAMInterstitialAd *ad, NSError *error) {
    if (error) {
      NSLog(@"interstitial:didFailToReceiveAdWithError: %@", [error localizedDescription])
      return;
    }
    self.interstitial = ad;
    self.interstitial.fullScreenContentDelegate = self;
  }];
}

- (void)adDidPresentFullScreenContent:(id)ad {
  NSLog(@"Ad did present full screen content.");
}

- (void)ad:(id)ad didFailToPresentFullScreenContentWithError:(NSError *)error {
  NSLog(@"Ad failed to present full screen content with error %@.", [error localizedDescription]);
}

- (void)adDidDismissFullScreenContent:(id)ad {
  NSLog(@"Ad did dismiss full screen content.");
}

Rewarded

Load ad

v7

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADRewardedAdDelegate {
  /// The rewarded ad.
  var rewardedAd: GADRewardedAd?

  override func viewDidLoad() {
    super.viewDidLoad()
    rewardedAd = GADRewardedAd(adUnitID: "ca-app-pub-3940256099942544/1712485313")
    rewardedAd.delegate = self
    rewardedAd?.load(GAMRequest()) { error in
      if let error = error {
        print("Rewarded ad failed to load with error: \(error.localizedDescription)")
      } else {
        print("Rewarded ad loaded.")
      }
    }
  }
}

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) GADRewardedAd *rewardedAd;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  self.rewardedAd = [[GADRewardedAd alloc]
      initWithAdUnitID:@"ca-app-pub-3940256099942544/1712485313"];
  self.rewardedAd.delegate = self;
  GAMRequest *request = [GAMRequest request];
  [self.rewardedAd loadRequest:request completionHandler:^(GADRequestError * _Nullable error) {
    if (error) {
      NSLog(@"Rewarded ad failed to load with error: %@", [error localizedDescription]);
    } else {
      NSLog(@"Rewarded ad loaded.");
    }
  }];
}

v8

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADFullScreenContentDelegate {
  /// The rewarded ad.
  var rewardedAd: GADRewardedAd?

  override func viewDidLoad() {
  super.viewDidLoad()
  let request = GAMRequest()
  GADRewardedAd.load(withAdUnitID: "ca-app-pub-8123415297019784/9501821136",
                          request: request, completionHandler: { (ad, error) in
                            if let error = error {
                              print("Rewarded ad failed to load with error: \(error.localizedDescription)")
                              return
                            }
                            self.rewardedAd = ad
                            self.rewardedAd?.fullScreenContentDelegate = self
                          }
  )
  }
}

Objective-C

@import GoogleMobileAds;
@import UIKit;

@interface ViewController () 

@property(nonatomic, strong) GADRewardedAd *rewardedAd;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  GAMRequest *request = [GAMRequest request];
  [GADRewardedAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/1712485313"
                          request:request
                completionHandler:^(GADRewardedAd *ad, NSError *error) {
    if (error) {
      NSLog(@"Rewarded ad failed to load with error: %@", [error localizedDescription]);
      return;
    }
    self.rewardedAd = ad;
    NSLog(@"Rewarded ad loaded.");
    self.rewardedAd.fullScreenContentDelegate = self;
}

Display ad and handle reward

Rewarded ads require you to handle the event when a user earns a reward. With version 7 of the GADRewardedAd API, you implement rewardedAd:userDidEarnReward: as part of the GADRewardedAdDelegate protocol. For version 8, you implement the GADUserDidEarnRewardHandler in order to present the ad.

v7

Swift

func showRewardedAd() {
  ...
  if rewardedAd.isReady {
    rewardedAd.present(fromRootViewController: self delegate:self)
  } else {
    print("Ad wasn't ready")
  }
}

/// Tells the delegate that the user earned a reward.
func rewardedAd(_ rewardedAd: GADRewardedAd, userDidEarnReward: GADAdReward) {
  // TODO: Reward the user.
}

Objective-C

- (void)showRewardedAd: {
  ...
  if (self.rewardedAd.isReady) {
    [self.rewardedAd presentFromRootViewController:self delegate:self];
  } else {
    NSLog(@"Ad wasn't ready");
  }
}

/// Tells the delegate that the user earned a reward.
- (void)rewardedAd:(GADRewardedAd *)rewardedAd userDidEarnReward:(GADAdReward *)reward {
  // TODO: Reward the user.
}

v8

Swift

func showRewardedAd() {
  ...
  if let ad = rewardedAd {
      ad.present(fromRootViewController: self,
               userDidEarnRewardHandler: {
                 let reward = ad.adReward
                 // TODO: Reward the user.
               }
      )
  } else {
    print("Ad wasn't ready")
  }
}

Objective-C

- (void)showRewardedAd: {
  ...
  if (self.rewardedAd) {
    [self.rewardedAd presentFromRootViewController:self
                          userDidEarnRewardHandler:^ {
      GADAdReward *reward = self.rewardedAd.adReward;
      // TODO: Reward the user.
    }];
  } else {
    NSLog(@"Ad wasn't ready");
  }
}

Presentation ad events

With the GADRewardedAd API you pass a GADRewardedAdDelegate to the method that presents the ad. With the GADRewardedAd API, you set a GADFullscreenContentDelegate as a property on the ad prior to presenting the ad.

v7

Swift

func showRewardedAd() {
  ...
  if rewardedAd.isReady {
    rewardedAd.present(fromRootViewController: self delegate:self)
  } else {
    print("Ad wasn't ready")
  }
}

/// Tells the delegate that the rewarded ad was presented.
func rewardedAdDidPresent(_ rewardedAd: GADRewardedAd) {
  print("Rewarded ad presented.")
}
/// Tells the delegate that the rewarded ad was dismissed.
func rewardedAdDidDismiss(_ rewardedAd: GADRewardedAd) {
  print("Rewarded ad dismissed.")
}
/// Tells the delegate that the rewarded ad failed to present.
func rewardedAd(_ rewardedAd: GADRewardedAd, didFailToPresentWithError error: Error) {
  print("Rewarded ad failed to present with error: \(error.localizedDescription).")
}

Objective-C

- (void)showRewardedAd: {
  ...
  if (self.rewardedAd.isReady) {
    [self.rewardedAd presentFromRootViewController:self delegate:self];
  } else {
    NSLog(@"Ad wasn't ready");
  }
}

/// Tells the delegate that the rewarded ad was presented.
- (void)rewardedAdDidPresent:(GADRewardedAd *)rewardedAd {
  NSLog(@"Rewarded ad presented.");
}

/// Tells the delegate that the rewarded ad failed to present.
- (void)rewardedAd:(GADRewardedAd *)rewardedAd didFailToPresentWithError:(NSError *)error {
  NSLog(@"Rewarded ad failed to present with error: %@",
        [error localizedDescription]);
}

/// Tells the delegate that the rewarded ad was dismissed.
- (void)rewardedAdDidDismiss:(GADRewardedAd *)rewardedAd {
  NSLog(@"Rewarded ad dismissed.");
}

v8

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  let request = GAMRequest()
  GADRewardedAd.load(withAdUnitID: "ca-app-pub-8123415297019784/9501821136",
                          request: request, completionHandler: { (ad, error) in
                            if let error = error {
                              print(error.localizedDescription)
                              return
                            }
                            self.rewardedAd = ad
                            self.rewardedAd?.fullScreenContentDelegate = self
                          }
  )
}

/// Tells the delegate that the rewarded ad was presented.
func adDidPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("Rewarded ad presented.")
}
/// Tells the delegate that the rewarded ad was dismissed.
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
  print("Rewarded ad dismissed.")
}
/// Tells the delegate that the rewarded ad failed to present.
func ad(_ ad: GADFullScreenPresentingAd,
    didFailToPresentFullScreenContentWithError error: Error) {
  print("Rewarded ad failed to present with error: \(error.localizedDescription).")
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];

  GAMRequest *request = [GAMRequest request];
  [GADRewardedAd loadWithAdUnitID:@"ca-app-pub-3940256099942544/1712485313"
                          request:request
                completionHandler:^(GADRewardedAd *ad, NSError *error) {
    if (error) {
      NSLog(@"Rewarded ad failed to load with error: %@", [error localizedDescription]);
      return;
    }
    self.rewardedAd = ad;
    NSLog(@"Rewarded ad loaded.");
    self.rewardedAd.fullScreenContentDelegate = self;
}

/// Tells the delegate that the rewarded ad was presented.
- (void)adDidPresentFullScreenContent:(id)ad {
  NSLog(@"Rewarded ad presented.");
}

/// Tells the delegate that the rewarded ad failed to present.
- (void)ad:(id)ad
    didFailToPresentFullScreenContentWithError:(NSError *)error {
  NSLog(@"Rewarded ad failed to present with error: %@",
       [error localizedDescription]);
}

/// Tells the delegate that the rewarded ad was dismissed.
- (void)adDidDismissFullScreenContent:(id)ad {
  NSLog(@"Rewarded ad dismissed.");
}

Legacy GADRewardedBasedVideoAd API removal

The newer GADRewardedAd API was first introduced back in March 2019 and has been the preferred rewarded API for over 18 months. It has had more enhancements compared to the legacy GADRewardedBasedVideoAd API, including the ability to load more than one rewarded ad at a time.

The legacy GADRewardedBasedVideoAd API is removed in SDK version 8.0.0.

Smart banner deprecation in favor of adaptive banner

Smart banner ads are deprecated in favor of adaptive banner ads. Adaptive banners provide superior performance and more flexibility in setting ad width. If you prefer to continue using full-width banners, that can still be done using adaptive banner, as shown in the following code snippet:

Swift

class ViewController: UIViewController {

  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    // Note: The safe area is not known until viewWillAppear.
    let adSize = getFullWidthAdaptiveAdSize()
  }

  func getFullWidthAdaptiveAdSize() -> GADAdSize {
    // Here safe area is taken into account, hence the view frame is used after the
    // view has been laid out.
    let frame = { () -> CGRect in
      if #available(iOS 11.0, *) {
        return view.frame.inset(by: view.safeAreaInsets)
      } else {
        return view.frame
      }
    }()
    return GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(frame.size.width)
  }
}

Objective-C

@implementation ViewController

- (void)viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];
  // Note: The safe area is not known until viewWillAppear.
  GADAdSize adSize = [self getFullWidthAdaptiveAdSize];
}

- (GADAdSize)getFullWidthAdaptiveAdSize {
  CGRect frame = self.view.frame;
  // Here safe area is taken into account, hence the view frame is used after
  // the view has been laid out.
  if (@available(iOS 11.0, *)) {
    frame = UIEdgeInsetsInsetRect(self.view.frame, self.view.safeAreaInsets);
  }
  return GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(frame.size.width);
}

@end

Leave application callback removal

The willLeaveApplication callback for all ad formats has been removed in favor of the applicationDidEnterBackground: and sceneDidEnterBackground: methods. Using OS-level APIs notify you whenever users leave your app, regardless of whether or not it is due to an ad interaction.

Note that the willLeaveApplication callback was never intended to be an ad click handler, and relying on this callback to report clicks did not produce an accurate metric. For example, a click on the AdChoices icon that launched an external browser invoked the callback but did not count a click.

Class renames

The table below lists specific class names that have changed or been removed in version 8. In summary:

  • All classes related to GADUnifiedNativeAd have been renamed to GADNativeAd.
  • GADRewardBasedVideoAd, GADNativeExpressAdView, and GADInstreamAd have been removed.
  • All classes with the DFP prefix have been replaced with a GAM prefix.
v7.68.0 Class v8.0.0 Class
DFPBannerView GAMBannerView
DFPBannerViewOptions GAMBannerViewOptions
DFPInterstitial GAMInterstitialAd
DFPRequest GAMRequest
GADRequestError NSError
GADUnifiedNativeAdView GADNativeAdView
GADUnifiedNativeAd GADNativeAd
GADUnifiedNativeAdAssetIdentifiers GADNativeAdAssetIdentifiers
GADUnifiedNativeAdDelegate GADNativeAdDelegate
GADUnifiedNativeAdUnconfirmedClickDelegate GADNativeAdUnconfirmedClickDelegate
GADNativeCustomTemplateAd GADCustomNativeAd
GADNativeCustomTemplateAdLoaderDelegate GADCustomNativeAdLoaderDelegate
GADNativeAdDelegate GADCustomNativeAdDelegate
GADInAppPurchase Removed
GADInterstitial GADInterstitialAd
GADNativeExpressAdView Removed
GADRewardBasedVideoAd Removed
GADInstreamAd Removed
GADInstreamAdView Removed

Methods removed/replaced

The table below lists the specific changes in version 8. In summary:

  • Previously deprecated methods and properties have been removed.
  • -willLeaveApplication: delegate methods have been removed for all formats.
  • The ad network class name has moved to the GADResponseInfo property.
  • The test device identifier has moved to the GADRequestConfiguration property.
v7.68.0 Class v7.68.0 API v8.0.0 API Notes
GADMobileAds +configureWithApplicationID: -startWithCompletionHandler: The app ID is now set in Info.plist.
+disableAutomatedInAppPurchaseReporting -disableAutomatedInAppPurchaseReporting
+disableSDKCrashReporting -disableSDKCrashReporting
GADRequest testDevices GADRequestConfiguration.testdeviceidentifiers The testDeviceIdentifiers property applies to all ad requests, while the old testDevices property was set per-request.
gender Removed
birthday Removed
+sdkVersion GADMobileAds.sharedInstance.sdkVersion
-setBirthdayWithMonth:day:year: Removed
-setLocationWithDescription: -setLocationWithLatitude:longitude:accuracy:
-tagForChildDirectedTreatment: [GADMobileAds.sharedInstance.requestConfiguration tagForChildDirectedTreatment]
GADErrorCode kGADError* GADError* The k prefix is dropped from all error code constants.
GADBannerView hasAutoRefreshed autoloadEnabled
inAppPurchaseDelegate Removed
mediatedAdView Removed
adNetworkClassName responseInfo.adNetworkClassName
DFPBannerView -setValidAdSizesWithSizes: -setValidAdSizes:
DFPBannerViewOptions -adSizeDelegate Removed
GADBannerViewDelegate -adViewDidReceiveAd: -bannerViewDidReceiveAd:
-adView:didFailToReceiveAdWithError: -bannerView:didFailToReceiveAdWithError:
-adViewWillPresentScreen: -bannerViewWillPresentScreen:
-adViewWillDismissScreen: -bannerViewWillDismissScreen:
-adViewDidDismissScreen: -bannerViewDidDismissScreen:
-adViewWillLeaveApplication: Removed
GADNativeCustomTemplateAd templateID GADCustomNativeAd.formatID
-performClickOnAssetWithKey:customClickHandler: -performClickOnAssetWithKey:
GADNativeAdImageAdLoaderOptions preferredImageOrientation GADNativeAdMediaAdOptions.mediaAspectRatio
GADInterstitial inAppPurchaseDelegate Removed
isReady Removed Use canPresentFromRootViewController:error: instead.
hasBeenUsed Removed
-init -initWithAdUnitID:
-setAdUnitID: -initWithAdUnitID:
adNetworkClassName responseInfo.adNetworkClassName
-interstitialWillLeaveApplication: Removed
GADUnifiedNativeAd videoController mediaContent.videoController
adNetworkClassName responseInfo.adNetworkClassName