Миграция версий SDK

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

This page covers migrations for current and previous versions of the Google Mobile Ads SDK for iOS. Version 12.0.0 is expected to be released in February 2025.

Переход с версии 11 на версию 12

Обновите Xcode до версии 16.0.

The minimum supported Xcode version has increased to 16.0.

Поддержка именования в Swift

В версии 12.0.0 внесены изменения, соответствующие правилам именования, изложенным в Руководстве по проектированию API Swift. Эти изменения затрагивают только Swift. В API Objective-C никаких изменений в именовании не внесено.

Изменения префикса класса

В префиксы классов внесены следующие изменения:

  • Удален префикс GAD из всех названий для всех типов.
  • Префикс GAM переименован в AdManager .
  • Префикс GADM был переименован в Mediation .

Устранение ошибок

Лучший способ устранить ошибки, возникшие в результате этих изменений, — внести исправления с помощью инструмента Fix-It .

Устранить конфликты имен.

Для разрешения конфликтов имен используйте пространство имен, предоставляемое модулем. Например, класс GADRequest теперь называется Request . Пример пространства имен класса Request Google Mobile Ads SDK :

import GoogleMobileAds
...
var request: GoogleMobileAds.Request?

Подробный список изменений в Swift

В следующих таблицах перечислены изменения, внесенные в API Swift:

Версия 11 Версия 12
GADAdapterInitializationState AdapterInitializationState
GADAdChoicesPosition AdChoicesPosition
GADAdChoicesView AdChoicesView
GADAdFormat AdFormat
GADAdLoader AdLoader
GADAdLoaderAdType AdLoaderAdType
GADAdLoaderDelegate AdLoaderDelegate
GADAdMetadataDelegate AdMetadataDelegate
GADAdMetadataProvider AdMetadataProvider
GADAdNetworkExtras AdNetworkExtras
GADAdNetworkResponseInfo AdNetworkResponseInfo
GADAdReward AdReward
GADAdSize AdSize
GADAdSizeDelegate AdSizeDelegate
GADAdValue AdValue
GADAdValuePrecision AdValuePrecision
GADAppEventDelegate AppEventDelegate
GADAppOpenAd AppOpenAd
GADAppOpenSignalRequest AppOpenSignalRequest
GADAudioVideoManager AudioVideoManager
GADAudioVideoManagerDelegate AudioVideoManagerDelegate
GADBannerSignalRequest BannerSignalRequest
GADBannerView BannerView
GADBannerViewDelegate BannerViewDelegate
GADCustomEventExtras CustomEventExtras
GADCustomEventRequest CustomEventRequest
GADCustomNativeAd CustomNativeAd
GADCustomNativeAdLoaderDelegate CustomNativeAdLoaderDelegate
GADCustomNativeAdDelegate CustomNativeAdDelegate
GADDebugOptionsViewControllerDelegate DebugOptionsViewControllerDelegate
GADDebugOptionsViewController DebugOptionsViewController
GADDisplayAdMeasurement DisplayAdMeasurement
GADExtras Extras
GADFullScreenPresentingAd FullScreenPresentingAd
GADFullScreenContentDelegate FullScreenContentDelegate
GADAdapterStatus AdapterStatus
GADInitializationStatus InitializationStatus
GADInterstitialAd InterstitialAd
GADInterstitialSignalRequest InterstitialSignalRequest
GADMediaAspectRatio MediaAspectRatio
GADMediaContent MediaContent
GADMediaView MediaView
GADMobileAds MobileAds
GADMultipleAdsAdLoaderOptions MultipleAdsAdLoaderOptions
GADMuteThisAdReason MuteThisAdReason
GADNativeAd NativeAd
GADNativeAdLoaderDelegate NativeAdLoaderDelegate
GADNativeAdView NativeAdView
GADNativeAdCustomClickGestureOptions NativeAdCustomClickGestureOptions
GADNativeAdDelegate NativeAdDelegate
GADNativeAdImage NativeAdImage
GADNativeAdImageAdLoaderOptions NativeAdImageAdLoaderOptions
GADNativeAdInlineBehavior NativeAdInlineBehavior
GADNativeAdInlineBehaviorOptions NativeAdInlineBehaviorOptions
GADNativeAdMediaAdLoaderOptions NativeAdMediaAdLoaderOptions
GADNativeAdUnconfirmedClickDelegate NativeAdUnconfirmedClickDelegate
GADNativeAdViewAdOptions NativeAdViewAdOptions
GADNativeMuteThisAdLoaderOptions NativeMuteThisAdLoaderOptions
GADNativeSignalRequest NativeSignalRequest
GADPresentationError PresentationError
GADPublisherPrivacyPersonalizationState PublisherPrivacyPersonalizationState
GADQueryInfo QueryInfo
GADRequest Request
GADRequestError RequestError
GADRequestConfiguration RequestConfiguration
GADResponseInfo ResponseInfo
GADRewardedAd RewardedAd
GADRewardedSignalRequest RewardedSignalRequest
GADRewardedInterstitialAd RewardedInterstitialAd
GADRewardedInterstitialSignalRequest RewardedInterstitialSignalRequest
GADSearchBannerView SearchBannerView
GADServerSideVerificationOptions ServerSideVerificationOptions
GADSignal Signal
GADSignalRequest SignalRequest
GADVersionNumber VersionNumber
GADVideoController VideoController
GADVideoControllerDelegate VideoControllerDelegate
Менеджер рекламы
GAMBannerAdLoaderDelegate AdManagerBannerAdLoaderDelegate
GAMBannerView AdManagerBannerView
GAMBannerViewOptions AdManagerBannerViewOptions
GAMInterstitialAd AdManagerInterstitialAd
GAMRequest AdManagerRequest
Медиация
GADMAdNetworkAdapter MediationAdNetworkAdapter
GADMAdNetworkConnector MediationAdNetworkConnector
GADMBannerAnimationType MediationBannerAnimationType
GADMediatedUnifiedNativeAd MediationUnifiedNativeAd
GADMediatedUnifiedNativeAdNotificationSource MediationUnifiedNativeAdNotificationSource
GADMediationAd MediationAd
GADMediationAdConfiguration MediationAdConfiguration
GADMediationAdEventDelegate MediationAdEventDelegate
GADMediationAdRequest MediationAdRequest
GADMediationAdapter MediationAdapter
GADMediationAppOpenAd MediationAppOpenAd
GADMediationAppOpenAdEventDelegate MediationAppOpenAdEventDelegate
GADMediationBannerAd MediationBannerAd
GADMediationBannerAdConfiguration MediationBannerAdConfiguration
GADMediationBannerAdEventDelegate MediationBannerAdEventDelegate
GADMediationCredentials MediationCredentials
GADMediationInterstitialAd MediationInterstitialAd
GADMediationInterstitialAdConfiguration MediationInterstitialAdConfiguration
GADMediationInterstitialAdEventDelegate MediationInterstitialAdEventDelegate
GADMediationNativeAd MediationNativeAd
GADMediationNativeAdConfiguration MediationNativeAdConfiguration
GADMediationNativeAdEventDelegate MediationNativeAdEventDelegate
GADMediationRewardedAd MediationRewardedAd
GADMediationRewardedAdConfiguration MediationRewardedAdConfiguration
GADMediationRewardedAdEventDelegate MediationRewardedAdEventDelegate
GADMediationServerConfiguration MediationServerConfiguration
Торги в режиме реального времени
GADRTBAdapter RTBAdapter
GADRTBMediationSignalsConfiguration RTBMediationSignalsConfiguration
GADRTBRequestParameters RTBRequestParameters

Константы

Версия 11 Версия 12
GADAdLoaderAdType.gamBanner AdLoaderAdType.adManagerBanner
GADAdSizeBanner AdSizeBanner
GADAdSizeFluid AdSizeFluid
GADAdSizeFullBanner AdSizeFullBanner
GADAdSizeInvalid AdSizeInvalid
GADAdSizeLargeBanner AdSizeLargeBanner
GADAdSizeLeaderboard AdSizeLeaderboard
GADAdSizeMediumRectangle AdSizeMediumRectangle
GADAdSizeSkyscraper AdSizeSkyscraper
GoogleMobileAdsVersionString GoogleMobileAdsVersion

Характеристики

Тип Версия 11 Версия 12
GADAdLoader loading isLoading
GADAudioVideoManager audioSessionApplicationManaged isAudioSessionApplicationManaged
GADBannerView autoloadEnabled isAutoloadEnabled
GADMobileAds sharedInstance shared
applicationMuted isApplicationMuted
GADMuteThisAdReason reasonDescription reason
GADNativeAd customMuteThisAdAvailable isCustomMuteThisAdAvailable
GADNativeAdCustomClickGestureOptions tapsAllowed areTapsAllowed
GADNativeAdImageAdLoaderOptions imageLoadingDisabled isImageLoadingDisabled
GADNativeMuteThisAdLoaderOptions customMuteThisAdRequested isCustomMuteThisAdRequested
GADNativeSignalRequest imageLoadingDisabled isImageLoadingDisabled
customMuteThisAdRequested isCustomMuteThisAdRequested
GADRequest neighboringContentURLStrings neighboringContentURLs
GADResponseInfo extrasDictionary extras
GADServerSideVerificationOptions customRewardString customRewardText
GADSignal signalString signal
GADSignalRequest neighboringContentURLStrings neighboringContentURLs
GADVideoController customControlsRequested areCustomControlsRequested
clickToExpandEnabled isClickToExpandEnabled
GADVideoOptions startMuted shouldStartMuted
customControlsRequested areCustomControlsRequested
clickToExpandRequested isClickToExpandRequested

Функции

Тип Версия 11 Версия 12
GADAdSize GADPortraitInlineAdaptiveBannerAdSizeWithWidth(_:) portraitInlineAdaptiveBanner(width:)
GADLandscapeInlineAdaptiveBannerAdSizeWithWidth(_:) landscapeInlineAdaptiveBanner(width:)
GADCurrentOrientationInlineAdaptiveBannerAdSizeWithWidth(_:) currentOrientationInlineAdaptiveBanner(width:)
GADInlineAdaptiveBannerAdSizeWithWidthAndMaxHeight(_:, _:) inlineAdaptiveBanner(width:maxHeight:)
GADPortraitAnchoredAdaptiveBannerAdSizeWithWidth(_:) portraitAnchoredAdaptiveBanner(width:)
GADLandscapeAnchoredAdaptiveBannerAdSizeWithWidth(_:) landscapeAnchoredAdaptiveBanner(width:)
GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(_:) currentOrientationAnchoredAdaptiveBanner(width:)
GADAdSizeFromCGSize(_:) adSizeFor(cgSize:)
GADAdSizeFullWidthPortraitWithHeight(_:) fullWidthPortrait(height:)
GADAdSizeFullWidthLandscapeWithHeight(_:) fullWidthLandscape(height:)
GADAdSizeEqualToSize(_:, _:) isAdSizeEqualToSize(size1:size2:)
IsGADAdSizeValid(_:) isAdSizeValid(size:)
GADAdSizeIsFluid(_:) isAdSizeFluid(size:)
CGSizeFromGADAdSize(_:) cgSize(for:)
NSStringFromGADAdSize(_:) string(for:)
NSValueFromGADAdSize(_:) nsValue(for:)
GADAdSizeFromNSValue(_:) adSizeFor(nsValue:)
GADClosestValidSizeForAdSizes(_:_:) closestValidSizeForAdSizes(original:possibleAdSizes:)
GADAppEventDelegate adView(_:didReceiveAppEvent:withInfo:) adView(_:didReceiveAppEvent:with:)
interstitialAd(_:didReceiveAppEvent:withInfo:) adView(_:didReceiveAppEvent:with:)
GADAppOpenAd load(withAdResponseString:) load(with:)
load(withAdUnitID:request:completionHandler:) load(with:request:completionHandler:)
canPresent(fromRootViewController:) canPresent(from:)
present(fromRootViewController:) present(from:)
GADBannerView load(withAdResponseString:) load(with:)
GADInterstitial load(withAdResponseString:) load(with:)
load(withAdUnitID:request:completionHandler:) load(with:request:completionHandler:)
canPresent(fromRootViewController:) canPresent(from:)
present(fromRootViewController:) present(from:)
GADRewardedAd load(withAdResponseString:) load(with:)
load(withAdUnitID:request:completionHandler:) load(with:request:completionHandler:)
canPresent(fromRootViewController:) canPresent(from:)
present(fromRootViewController:userDidEarnRewardHandler:) present(from:userDidEarnRewardHandler:)
GADRewardedIntertitialAd load(withAdResponseString:) load(with:)
load(withAdUnitID:request:completionHandler:) load(with:request:completionHandler:)
canPresent(fromRootViewController:) canPresent(from:)
present(fromRootViewController:userDidEarnRewardHandler:) present(from:userDidEarnRewardHandler:)
GADVersionNumber GADGetStringFromVersionNumber(_ version: GADVersionNumber) string(for:)
Медиация
GADMAdNetworkAdapter getBannerWith(_:) getBanner(with:)
presentInterstitial(fromRootViewController:) presentInterstitial(from:)
getNativeAd(withAdTypes:options:) getNativeAd(with:options:)
GADMediatedUnifiedNativeAd didRecordClickOnAsset(withName:view:viewController:) didRecordClickOnAsset(with:view:viewController:)
GADMediationAdapter setUpWith(_:completionHandler:) setUp(with:completionHandler:)
GADMediationAdSize present(fromRootViewController:) present(from:)
GADMediationAppOpenAd present(fromRootViewController:) present(from:)
GADMediationInterstitialAd present(fromRootViewController:) present(from:)
GADMediationRewardedAd present(fromRootViewController:) present(from:)
GAMIntersticialAd load(withAdManagerAdUnitID:request:completionHandler:) load(with:request:completionHandler:)

Задайте пользовательские параметры таргетинга

Для настройки пользовательского таргетинга для запроса объявления используйте customTargeting .

Изменения в API для управления состоянием отключения звука видео.

Свойство isMuted и метод setMute: в классе GADVideoController заменены свойством muted .

Изменения в адаптивной рекламе, размещаемой непосредственно в тексте.

Для оптимизации использования пространства встроенные адаптивные объявления изначально не занимают места во фрейме. Вызов функции CGSizeFromGADAdSize(_:) с заданным размером встроенного адаптивного объявления теперь возвращает 0 высоту до тех пор, пока SDK Google Mobile Ads не вернет объявление.

Удалены объявления, созданные для пользовательского поиска.

Следующие классы удаляются без замены:

  • GADDynamicHeightSearchBannerView
  • GADDynamicHeightSearchRequest
  • GADSearchBannerView

Изменения в кодах ошибок

Изменены следующие коды ошибок:

Сорт Примечания
GADErrorMediationNoFill Теперь ошибки возвращаются как GADErrorNoFill .
GADErrorReceivedInvalidResponse Заменено на GADErrorReceivedInvalidAdString .

Удалён GADSimulatorID

Удалён GADSimulatorID . Симуляторы по умолчанию уже находятся в тестовом режиме.

Изменения в пользовательском таргетинге

В словаре customTargeting в GADRequest теперь используется тип значения Any вместо String . Это позволяет передавать числовые значения в API.

Изменения дополнительных параметров

Переход с версии 10 на версию 11

Минимальный целевой показатель развертывания

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

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

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

Реклама перестала показываться в iOS 12.

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

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

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

Изменения в отображении полноэкранной рекламы.

Следующие изменения касаются различных форматов рекламы:

  • Приложение открыто
  • Интерстициальный
  • Награжден
  • Вознагражденный интерстициальный

Параметр контроллера представления в -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) Замена не предусмотрена.
GADRequestConfiguration setSameAppKeyEnabled(_ enabled: Bool) Вместо этого используйте setPublisherFirstPartyIDEnabled(_ enabled: Bool) .
tagForUnderAge(ofConsent underAgeOfConsent: Bool) Вместо этого используйте свойство tagForUnderAgeOfConsent .
tag(forChildDirectedTreatment childDirectedTreatment: Bool) Вместо этого используйте свойство tagForChildDirectedTreatment .

Удаленные свойства

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

v11.0.0 Класс Свойство Примечания
GADMediationAdConfiguration hasUserLocation Замена не предусмотрена.
userLatitude
долгота пользователя
userLocationAccuracyInMeters
лечение, направленное на ребенка Вместо этого используйте GADMobileAds.sharedInstance.requestConfiguration.tagForChildDirectedTreatment .
GADResponseInfo adNetworkClassName Вместо этого используйте 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 .
  • Данное устройство представляет собой симулятор.
  • The device is explicitly declared as a test device in the Ad Manager UI.

Переход с версии 9 на версию 10

Реклама перестала показываться в iOS 11.

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

Upgrading to Google Mobile Ads SDK version 10.0.0 will not break your app on iOS 11 and iOS 10 devices, however, no ads will be served on those devices.

Требуется идентификатор приложения Ad Manager.

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

Требование к фреймворку GoogleAppMeasurement.xc

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

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

Disabling bitcode in your mobile apps is now required to integrate the Google Mobile Ads SDK .

Удаленные типы

Тип Примечания
ГАДГендер Замена не предусмотрена.
GADMRewardBasedVideoAdNetworkAdapterProtocol All rewarded mediation adapters listed on Choose Networks have stopped using these protocols for over a year. Use GADMediationAdapter for mediation and custom events.
GADMRewardBasedVideoAdNetworkConnectorProtocol

Удаленные свойства

The following properties are removed with no replacement.

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

Переход с версии 8 на версию 9

Реклама перестала показываться в iOS 10.

The minimum iOS version Google Mobile Ads SDK version 9.0.0 supports is iOS 11.

Upgrading to Google Mobile Ads SDK version 9.0.0 will not break your app on iOS 10 devices, however, no ads will be served on those devices.

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

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

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

Rename adDidPresentFullScreenContent: to adWillPresentFullScreenContent:

There is no behavior change. The delegate method is invoked right before the ad is about to be presented, so the new method name better reflects its functionality.

Удалить API для установки местоположения из GADRequest.

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

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

Custom events enable publishers using Ad Manager Mediation to add waterfall mediation for an ad network that isn't one of the supported ad networks .

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

API

The table below lists the corresponding mediation adapter APIs to custom events APIs that should be used starting from version 9.0.0.

v8 v9
GADCustomEventBanner
GADCustomEventInterstitial
GADCustomEventNativeAd
GADMediationAdapter GADMediationBannerAd
GADMediationInterstitialAd
GADMediationInterscrollerAd
GADMediationRewardedAd
GADMediationNativeAd
delegate Delegate is returned by the load completion handler of each load function of GADMediationAdapter class
-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

Методы делегирования

The table below lists the corresponding mediation ad event delegate methods to custom event delegate methods that should be used starting from version 9.0.0.

v8 v9
GADCustomEventBannerDelegate
GADCustomEventInterstitialDelegate
GADCustomEventNativeAdDelegate
GADMediationAdEventDelegate GADMediationAd
-customEventBanner:didReceiveAd:
-customEventInterstitialDidReceiveAd:
Ad load status is included in the load completion handler of each load function in the GADMediationAdapter class
-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 were removed. Use adUnitMapping instead.
GAMRequest kGAMSimulatorID in GAMRequest is deprecated. Use GADSimulatorID in GADRequestConfiguration instead.
GADCustomNativeAd mediaView in GADCustomNativeAd is deprecated. Use mediaContent instead.
API для встроенных покупок в GoogleMobileAds inAppPurchase APIs in GoogleMobileAds were removed.

Переход с версии 7 на версию 8

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

Обновления API для полноэкранного формата

Начиная с версии 8.0.0, межстраничные и рекламные объявления с вознаграждением используют единый стиль полноэкранных объявлений для большей согласованности. Эти новые API для полноэкранных объявлений имеют два основных отличия от API полноэкранных объявлений версии 7:

  1. 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. Загрузить рекламу.
    4. Проверьте, загружена ли реклама, используя isReady .
    5. Покажите рекламу.

    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. Назначьте делегата, который будет обрабатывать обратные вызовы шоу.
    4. Покажите рекламу.

    Новый подход обеспечивает следующие преимущества:

    • 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. Постоянные рекламные события.

    Тип события Существующий API API v8
    Загрузка событий GADInterstitialDelegate или GADRewardedAdDelegate GAMInterstitialAdLoadCompletionHandler or GADRewardedAdLoadCompletionHandler
    Презентационные мероприятия GADFullScreenContentDelegate

    Ранее для отслеживания событий, связанных с рекламой, необходимо было зарегистрировать класс, реализующий протокол GADInterstitialDelegate , в свойстве delegate межстраничной рекламы или класс, реализующий протокол GADRewardedAdDelegate , в свойстве delegate рекламы с вознаграждением, в зависимости от используемого формата. Этот же делегат содержал методы, связанные как с циклом загрузки, так и с циклом отображения рекламы.

    В версии 8 события загрузки и отображения разделены. Теперь вы можете зарегистрировать GADFullScreenContentDelegate в любое время до показа рекламы, вместо того чтобы устанавливать отдельный делегат перед загрузкой рекламы. События загрузки рекламы, специфичные для каждого формата, переносятся в единый обработчик завершения загрузки, передаваемый в метод загрузки.

Интерстициальный

Загрузить рекламу

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

Быстрый

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

Быстрый

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

Показывать рекламу

v7

Быстрый

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

Быстрый

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

Презентации рекламных мероприятий

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

v7

Быстрый

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

Быстрый

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

Награжден

Загрузить рекламу

v7

Быстрый

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

Быстрый

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

Показать рекламу и обработать вознаграждение

Для показа рекламы с вознаграждением необходимо обрабатывать событие, когда пользователь получает вознаграждение. В версии 7 API GADRewardedAd необходимо реализовать rewardedAd:userDidEarnReward: в рамках протокола GADRewardedAdDelegate . В версии 8 для показа рекламы необходимо реализовать метод GADUserDidEarnRewardHandler .

v7

Быстрый

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

Быстрый

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

Презентации рекламных мероприятий

При использовании API GADRewardedAd вы передаете GADRewardedAdDelegate методу, который отображает рекламу. Также с помощью API GADRewardedAd вы устанавливаете GADFullscreenContentDelegate в качестве свойства рекламы перед ее показом.

v7

Быстрый

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

Быстрый

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

Удаление устаревшего API GADRewardedBasedVideoAd

Новый API GADRewardedAd был впервые представлен в марте 2019 года и уже более 18 месяцев является предпочтительным API для рекламы с вознаграждением. По сравнению с устаревшим API GADRewardedBasedVideoAd он получил больше улучшений, включая возможность загрузки более чем одной рекламы с вознаграждением одновременно.

The legacy GADRewardedBasedVideoAd API is removed in SDK version 8.0.0.

Smart banner deprecation in favor of adaptive banner

Использование «умных» баннеров устарело, в пользу «адаптивных» баннеров . Адаптивные баннеры обеспечивают более высокую производительность и большую гибкость в настройке ширины объявления. Если вы предпочитаете продолжать использовать баннеры во всю ширину экрана, это по-прежнему можно сделать с помощью адаптивных баннеров, как показано в следующем фрагменте кода:

Быстрый

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

Удаление обратного вызова приложения для отказа

Функция обратного вызова willLeaveApplication для всех форматов рекламы была удалена в пользу методов applicationDidEnterBackground: и sceneDidEnterBackground: :. Использование API на уровне операционной системы позволяет получать уведомления всякий раз, когда пользователи покидают ваше приложение, независимо от того, связано ли это с взаимодействием с рекламой или нет.

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

Переименование классов

В таблице ниже перечислены конкретные названия классов, которые изменились или были удалены в версии 8. Вкратце:

  • Все классы, связанные с GADUnifiedNativeAd были переименованы в GADNativeAd .
  • GADRewardBasedVideoAd , GADNativeExpressAdView и GADInstreamAd были удалены.
  • Все классы с префиксом DFP были заменены на классы с префиксом GAM .
v7.68.0 Класс v8.0.0 Класс
DFPBannerView GAMBannerView
DFPBannerViewOptions GAMBannerViewOptions
DFPIntersticial GAMIntersticialAd
DFPRequest GAMRequest
GADRequestError NSError
GADUnifiedNativeAdView GADNativeAdView
GADUnifiedNativeAd GADNativeAd
GADUnifiedNativeAdAssetIdentifiers GADNativeAdAssetIdentifiers
GADUnifiedNativeAdDelegate GADNativeAdDelegate
GADUnifiedNativeAdUnconfirmedClickDelegate GADNativeAdUnconfirmedClickDelegate
GADNativeCustomTemplateAd GADCustomNativeAd
GADNativeCustomTemplateAdLoaderDelegate GADCustomNativeAdLoaderDelegate
GADNativeAdDelegate GADCustomNativeAdDelegate
GADInAppPurchase Удаленный
GADInterstitial GADInterstitialAd
GADNativeExpressAdView Удаленный
GADRewardBasedVideoAd Удаленный
GADInstreamAd Удаленный
GADInstreamAdView Удаленный

Удаленные/замененные методы

В таблице ниже перечислены конкретные изменения в версии 8. Вкратце:

  • Ранее устаревшие методы и свойства были удалены.
  • -willLeaveApplication: методы делегата были удалены для всех форматов.
  • Название класса рекламной сети перемещено в свойство GADResponseInfo .
  • Идентификатор тестового устройства перемещен в свойство GADRequestConfiguration .
v7.68.0 Класс API версии 7.68.0 API версии 8.0.0 Примечания
GADMobileAds +configureWithApplicationID: -startWithCompletionHandler: Идентификатор приложения теперь задаётся в файле Info.plist.
+отключить автоматическую отчетность по покупкам в приложении -disableAutomatedInApp PurchaseReports
+disableSDKCrashReporting -disableSDKCrashReporting
GADRequest тестовые устройства GADRequestConfiguration .testdeviceidentifiers Свойство testDeviceIdentifiers применяется ко всем запросам рекламы, тогда как старое свойство testDevices устанавливалось для каждого запроса отдельно.
пол Удаленный
день рождения Удаленный
+sdkVersion GADMobileAds.sharedInstance .sdkVersion
-setBirthday WithMonth:day:year: Удаленный
-setLocationWithDescription: -setLocationWith Latitude:longitude:accuracy:
-tagForChildDirectedTreatment: [GADMobileAds.sharedInstance.requestConfiguration tagForChildDirectedTreatment]
GADErrorCode kGADError* GADError* Префикс k удаляется из всех констант кодов ошибок.
GADBannerView hasAutoRefreshed автозагрузкаВключено
inAppPurchaseDelegate Удаленный
mediatedAdView Удаленный
adNetworkClassName responseInfo .adNetworkClassName
DFPBannerView -setValidAdSizesWithSizes: -setValidAdSizes:
DFPBannerViewOptions -adSizeDelegate Удаленный
GADBannerViewDelegate -adViewDidReceiveAd: -bannerViewDidReceiveAd:
-adView:didFailToReceive AdWithError: -bannerView:didFailToReceive AdWithError:
-adViewWillPresentScreen: -bannerViewWillPresentScreen:
-adViewWillDismissScreen: -bannerViewWillDismissScreen:
-adViewDidDismissScreen: -bannerViewDidDismissScreen:
-adViewWillLeaveApplication: Удаленный
GADNativeCustomTemplateAd templateID GADCustomNativeAd.formatID
-performClickOnAssetWithKey: customClickHandler: -performClickOnAssetWithKey:
GADNativeAdImageAd LoaderOptions предпочтительная ориентация изображения GADNativeAdMediaAdOptions .mediaAspectRatio
GADInterstitial inAppPurchaseDelegate Удаленный
готов Удаленный Вместо этого используйте canPresentFromRootViewController:error:.
hasBeenUsed Удаленный
-инициализация -initWithAdUnitID:
-setAdUnitID: -initWithAdUnitID:
adNetworkClassName responseInfo .adNetworkClassName
-interstitialWill LeaveApplication: Удаленный
GADUnifiedNativeAd видеоконтроллер mediaContent.videoController
adNetworkClassName responseInfo .adNetworkClassName