Предпосылки
Завершите настройку пользовательских событий .
Запросить межстраничное объявление
Когда в цепочке посредничества водопада достигается элемент строки пользовательского события, вызываетсяthe loadInterstitial:adConfiguration:completionHandler:
method для имени класса, которое вы указали при создании пользовательского события . В данном случае этот метод находится в SampleCustomEvent
, который затем вызываетthe loadInterstitial:adConfiguration:completionHandler:
method в SampleCustomEventInterstitial
.
Чтобы запросить межстраничное объявление, создайте или измените класс, реализующий GADMediationAdapter
и loadInterstitial:adConfiguration:completionHandler:
. Если класс, расширяющий GADMediationAdapter
, уже существует, реализуйте loadInterstitial:adConfiguration:completionHandler:
там. Кроме того, создайте новый класс для реализации GADMediationInterstitialAd
.
В нашем примере пользовательского события SampleCustomEvent
реализуетthe GADMediationAdapter
interface , а затем делегируетSampleCustomEventInterstitial
.
Быстрый
import GoogleMobileAds class SampleCustomEvent: NSObject, GADMediationAdapter { fileprivate var interstitialAd: SampleCustomEventInterstitial? ... func loadInterstitial( for adConfiguration: GADMediationInterstitialAdConfiguration, completionHandler: @escaping GADMediationInterstitialLoadCompletionHandler ) { self.interstitialAd = SampleCustomEventInterstitial() self.interstitialAd?.loadInterstitial( for: adConfiguration, completionHandler: completionHandler) } }
Цель-C
#import "SampleCustomEvent.h" @implementation SampleCustomEvent SampleCustomEventInterstitial *sampleInterstitial; - (void)loadInterstitialForAdConfiguration: (GADMediationInterstitialAdConfiguration *)adConfiguration completionHandler: (GADMediationInterstitialLoadCompletionHandler) completionHandler { sampleInterstitial = [[SampleCustomEventInterstitial alloc] init]; [sampleInterstitial loadInterstitialForAdConfiguration:adConfiguration completionHandler:completionHandler]; }
SampleCustomEventInterstitial
отвечает за следующие задачи:
Загрузка межстраничного объявления и вызов
GADMediationInterstitialAdLoadCompletionHandler
method после завершения загрузкиРеализация
GADMediationInterstitialAd
protocolПолучение и отправка обратных вызовов рекламных событий в Google Mobile Ads SDK
Необязательный параметр, определенный в пользовательском интерфейсе Ad Manager , передается в ваше пользовательское событие как часть the loadInterstitial:adConfiguration:completionHandler:
method. Доступ к параметру можно получить через adConfiguration.credentials.settings[@"parameter"]
. Этот параметр обычно является идентификатором рекламного блока, который требуется SDK рекламной сети при создании объекта объявления.
Быстрый
import GoogleMobileAds class SampleCustomEventInterstitial: NSObject, GADMediationInterstitialAd { /// The Sample Ad Network interstitial ad. var interstitial: SampleInterstitial? /// The ad event delegate to forward ad rendering events to the Google Mobile Ads SDK. var delegate: GADMediationInterstitialAdEventDelegate? var completionHandler: GADMediationInterstitialLoadCompletionHandler? func loadInterstitial( for adConfiguration: GADMediationInterstitialAdConfiguration, completionHandler: @escaping GADMediationInterstitialLoadCompletionHandler ) { interstitial = SampleInterstitial.init( adUnitID: adConfiguration.credentials.settings["parameter"] as? String) interstitial?.delegate = self let adRequest = SampleAdRequest() adRequest.testMode = adConfiguration.isTestRequest self.completionHandler = completionHandler interstitial?.fetchAd(adRequest) } func present(from viewController: UIViewController) { if let interstitial = interstitial, interstitial.isInterstitialLoaded { interstitial.show() } } }
Цель-C
#import "SampleCustomEventInterstitial.h" @interface SampleCustomEventInterstitial () <SampleInterstitialAdDelegate, GADMediationInterstitialAd> { /// The sample interstitial ad. SampleInterstitial *_interstitialAd; /// The completion handler to call when the ad loading succeeds or fails. GADMediationInterstitialLoadCompletionHandler _loadCompletionHandler; /// The ad event delegate to forward ad rendering events to the Google Mobile /// Ads SDK. id <GADMediationInterstitialAdEventDelegate> _adEventDelegate; } @end - (void)loadInterstitialForAdConfiguration: (GADMediationInterstitialAdConfiguration *)adConfiguration completionHandler: (GADMediationInterstitialLoadCompletionHandler) completionHandler { __block atomic_flag completionHandlerCalled = ATOMIC_FLAG_INIT; __block GADMediationInterstitialLoadCompletionHandler originalCompletionHandler = [completionHandler copy]; _loadCompletionHandler = ^id<GADMediationInterstitialAdEventDelegate>( _Nullable id<GADMediationInterstitialAd> ad, NSError *_Nullable error) { // Only allow completion handler to be called once. if (atomic_flag_test_and_set(&completionHandlerCalled)) { return nil; } id<GADMediationInterstitialAdEventDelegate> delegate = nil; if (originalCompletionHandler) { // Call original handler and hold on to its return value. delegate = originalCompletionHandler(ad, error); } // Release reference to handler. Objects retained by the handler will also // be released. originalCompletionHandler = nil; return delegate; }; NSString *adUnit = adConfiguration.credentials.settings[@"parameter"]; _interstitialAd = [[SampleInterstitial alloc] initWithAdUnitID:adUnit]; _interstitialAd.delegate = self; SampleAdRequest *adRequest = [[SampleAdRequest alloc] init]; adRequest.testMode = adConfiguration.isTestRequest; [_interstitialAd fetchAd:adRequest]; }
Независимо от того, успешно ли получено объявление или возникла ошибка, вы должны вызвать GADMediationInterstitialLoadCompletionHandler
. В случае успеха пройти через класс, реализующий GADMediationInterstitialAd
, с nil
значением параметра error; в случае неудачи пройти через ошибку, с которой вы столкнулись.
Как правило, эти методы реализуются внутри обратных вызовов из стороннего пакета SDK, реализуемого вашим адаптером. В этом примере Sample SDK имеет SampleInterstitialAdDelegate
с соответствующими обратными вызовами:
Быстрый
func interstitialDidLoad(_ interstitial: SampleInterstitial) { if let handler = completionHandler { delegate = handler(self, nil) } } func interstitial( _ interstitial: SampleInterstitial, didFailToLoadAdWith errorCode: SampleErrorCode ) { let error = SampleCustomEventUtilsSwift.SampleCustomEventErrorWithCodeAndDescription( code: SampleCustomEventErrorCodeSwift .SampleCustomEventErrorAdLoadFailureCallback, description: "Sample SDK returned an ad load failure callback with error code: \(errorCode)" ) if let handler = completionHandler { delegate = handler(nil, error) } }
Цель-C
- (void)interstitialDidLoad:(SampleInterstitial *)interstitial { _adEventDelegate = _loadCompletionHandler(self, nil); } - (void)interstitial:(SampleInterstitial *)interstitial didFailToLoadAdWithErrorCode:(SampleErrorCode)errorCode { NSError *error = SampleCustomEventErrorWithCodeAndDescription( SampleCustomEventErrorAdLoadFailureCallback, [NSString stringWithFormat:@"Sample SDK returned an ad load failure " @"callback with error code: %@", errorCode]); _adEventDelegate = _loadCompletionHandler(nil, error); }
GADMediationInterstitialAd
требует реализации present
метода для отображения рекламы:
Быстрый
func present(from viewController: UIViewController) { if let interstitial = interstitial, interstitial.isInterstitialLoaded { interstitial.show() } }
Цель-C
- (void)presentFromViewController:(UIViewController *)viewController { if ([_interstitialAd isInterstitialLoaded]) { [_interstitialAd show]; } else { NSError *error = SampleCustomEventErrorWithCodeAndDescription( SampleCustomEventErrorAdNotLoaded, [NSString stringWithFormat:@"The interstitial ad failed to present " @"because the ad was not loaded."]); [_adEventDelegate didFailToPresentWithError:error] } }
Перенаправлять события агрегатора в Google Mobile Ads SDK
После того как вы вызвали GADMediationInterstitialLoadCompletionHandler
с загруженным объявлением, возвращенный объект делегата GADMediationInterstitialAdEventDelegate
может использоваться адаптером для пересылки событий презентации из стороннего SDK в SDK Google Mobile Ads. Класс SampleCustomEventInterstitial
реализует протокол SampleInterstitialAdDelegate
для переадресации обратных вызовов из примера рекламной сети в SDK Google Mobile Ads.
Важно, чтобы ваше пользовательское событие перенаправляло как можно больше таких обратных вызовов, чтобы ваше приложение получало эти эквивалентные события из Google Mobile Ads SDK. Вот пример использования обратных вызовов:
Быстрый
func interstitialWillPresentScreen(_ interstitial: SampleInterstitial) { delegate?.willPresentFullScreenView() delegate?.reportImpression() } func interstitialWillDismissScreen(_ interstitial: SampleInterstitial) { delegate?.willDismissFullScreenView() } func interstitialDidDismissScreen(_ interstitial: SampleInterstitial) { delegate?.didDismissFullScreenView() } func interstitialWillLeaveApplication(_ interstitial: SampleInterstitial) { delegate?.reportClick() }
Цель-C
- (void)interstitialWillPresentScreen:(SampleInterstitial *)interstitial { [_adEventDelegate willPresentFullScreenView]; [_adEventDelegate reportImpression]; } - (void)interstitialWillDismissScreen:(SampleInterstitial *)interstitial { [_adEventDelegate willDismissFullScreenView]; } - (void)interstitialDidDismissScreen:(SampleInterstitial *)interstitial { [_adEventDelegate didDismissFullScreenView]; } - (void)interstitialWillLeaveApplication:(SampleInterstitial *)interstitial { [_adEventDelegate reportClick]; }
На этом реализация пользовательских событий для межстраничных объявлений завершена. Полный пример доступен на GitHub . Вы можете использовать его с рекламной сетью, которая уже поддерживается, или изменить ее для отображения промежуточных объявлений с пользовательскими событиями.