배너 광고 맞춤 이벤트

기본 요건

맞춤 이벤트 설정을 완료합니다.

배너 광고 요청

폭포식 구조 미디에이션 체인에서 맞춤 이벤트 광고 항목에 도달하면 맞춤 이벤트를 생성할 때 제공한 클래스 이름에 대해the loadBanner:adConfiguration:completionHandler: method 가 호출됩니다. 이때 이 메서드는 SampleCustomEvent에 있고 SampleCustomEventBanner에서the loadBanner:adConfiguration:completionHandler: method 를 호출합니다.

배너 광고를 요청하려면 GADMediationAdapterloadBanner:adConfiguration:completionHandler:를 구현하는 클래스를 만들거나 수정하세요. GADMediationAdapter를 확장하는 클래스가 이미 있다면 그 클래스에 loadBanner:adConfiguration:completionHandler:를 구현합니다. 또한 GADMediationBannerAd를 구현할 새 클래스를 만듭니다.

맞춤 이벤트 예에서 SampleCustomEvent는the GADMediationAdapter interface 를 구현한 다음SampleCustomEventBanner에 위임합니다.

Swift

import GoogleMobileAds

class SampleCustomEvent: NSObject, GADMediationAdapter {

  fileprivate var bannerAd: SampleCustomEventBanner?
  ...

  func loadBanner(
    for adConfiguration: GADMediationBannerAdConfiguration,
    completionHandler: @escaping GADMediationBannerLoadCompletionHandler
  ) {
    self.bannerAd = SampleCustomEventBanner()
    self.bannerAd?.loadBanner(
      for: adConfiguration, completionHandler: completionHandler)
  }
}

Objective-C

#import "SampleCustomEvent.h"

@implementation SampleCustomEvent
...

SampleCustomEventBanner *sampleBanner;

- (void)loadBannerForAdConfiguration:
            (GADMediationBannerAdConfiguration *)adConfiguration
                   completionHandler:(GADMediationBannerLoadCompletionHandler)
                                         completionHandler {
  sampleBanner = [[SampleCustomEventBanner alloc] init];
  [sampleBanner loadBannerForAdConfiguration:adConfiguration
                           completionHandler:completionHandler];
}

SampleCustomEventBanner 는 다음 작업을 담당합니다.

  • 로드가 완료된 후 배너 광고를 로드하고 GADMediationBannerLoadCompletionHandler method 호출

  • GADMediationBannerAd protocol구현

  • Google 모바일 광고 SDK에 광고 이벤트 콜백 수신 및 보고

Ad Manager UI에 정의된 선택적 매개변수는 the loadBanner:adConfiguration:completionHandler: method의 일부로 맞춤 이벤트에 전달됩니다. adConfiguration.credentials.settings[@"parameter"]를 통해 매개변수에 액세스할 수 있습니다. 이 매개변수는 일반적으로 광고 네트워크 SDK가 광고 객체를 인스턴스화할 때 필요한 광고 단위 식별자입니다.

Swift

class SampleCustomEventBanner: NSObject, GADMediationBannerAd {
  /// The Sample Ad Network banner ad.
  var bannerAd: SampleBanner?

  /// The ad event delegate to forward ad rendering events to the Google Mobile Ads SDK.
  var delegate: GADMediationBannerAdEventDelegate?

  /// Completion handler called after ad load
  var completionHandler: GADMediationBannerLoadCompletionHandler?

  func loadBanner(
    for adConfiguration: GADMediationBannerAdConfiguration,
    completionHandler: @escaping GADMediationBannerLoadCompletionHandler
  ) {
    // Create the bannerView with the appropriate size.
    let adSize = adConfiguration.adSize
    bannerAd = SampleBanner(
      frame: CGRect(x: 0, y: 0, width: adSize.size.width, height: adSize.size.height))
    bannerAd?.delegate = self
    bannerAd?.adUnit = adConfiguration.credentials.settings["parameter"] as? String
    let adRequest = SampleAdRequest()
    adRequest.testMode = adConfiguration.isTestRequest
    self.completionHandler = completionHandler
    bannerAd?.fetchAd(adRequest)
  }
}

Objective-C

#import "SampleCustomEventBanner.h"

@interface SampleCustomEventBanner () <SampleBannerAdDelegate,
                                       GADMediationBannerAd> {
  /// The sample banner ad.
  SampleBanner *_bannerAd;

  /// The completion handler to call when the ad loading succeeds or fails.
  GADMediationBannerLoadCompletionHandler _loadCompletionHandler;

  /// The ad event delegate to forward ad rendering events to the Google Mobile
  /// Ads SDK.
  id <GADMediationBannerAdEventDelegate> _adEventDelegate;
}
@end

@implementation SampleCustomEventBanner

- (void)loadBannerForAdConfiguration:
            (GADMediationBannerAdConfiguration *)adConfiguration
                   completionHandler:(GADMediationBannerLoadCompletionHandler)
                                         completionHandler {
  __block atomic_flag completionHandlerCalled = ATOMIC_FLAG_INIT;
  __block GADMediationBannerLoadCompletionHandler originalCompletionHandler =
      [completionHandler copy];

  _loadCompletionHandler = ^id<GADMediationBannerAdEventDelegate>(
      _Nullable id<GADMediationBannerAd> ad, NSError *_Nullable error) {
    // Only allow completion handler to be called once.
    if (atomic_flag_test_and_set(&completionHandlerCalled)) {
      return nil;
    }

    id<GADMediationBannerAdEventDelegate> 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"];
  _bannerAd = [[SampleBanner alloc]
      initWithFrame:CGRectMake(0, 0, adConfiguration.adSize.size.width,
                               adConfiguration.adSize.size.height)];
  _bannerAd.adUnit = adUnit;
  _bannerAd.delegate = self;
  SampleAdRequest *adRequest = [[SampleAdRequest alloc] init];
  adRequest.testMode = adConfiguration.isTestRequest;
  [_bannerAd fetchAd:adRequest];
}

광고를 성공적으로 가져왔거나 오류가 발생하면 GADMediationBannerLoadCompletionHandler를 호출합니다. 성공하면 오류 매개변수의 nil 값과 함께 GADMediationBannerAd를 구현하는 클래스를 전달합니다. 실패하면 발생한 오류를 전달합니다.

일반적으로 이러한 메서드는 어댑터가 구현하는 서드 파티 SDK의 콜백 내에서 구현됩니다. 이 예의 샘플 SDK에는 관련 콜백이 있는 SampleBannerAdDelegate가 있습니다.

Swift

func bannerDidLoad(_ banner: SampleBanner) {
  if let handler = completionHandler {
    delegate = handler(self, nil)
  }
}

func banner(
  _ banner: SampleBanner, 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)
  }
}

Objective-C

- (void)bannerDidLoad:(SampleBanner *)banner {
  _adEventDelegate = _loadCompletionHandler(self, nil);
}

- (void)banner:(SampleBanner *)banner
    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);
}

GADMediationBannerAd를 사용하려면 다음과 같이 UIView 속성을 구현해야 합니다.

Swift

var view: UIView {
  return bannerAd ?? UIView()
}

Objective-C

- (nonnull UIView *)view {
  return _bannerAd;
}

Google 모바일 광고 SDK에 미디에이션 이벤트 전달

로드된 광고로 GADMediationBannerLoadCompletionHandler를 호출한 후에는 어댑터가 반환된 GADMediationBannerAdEventDelegate 대리자 객체를 사용하여 프레젠테이션 이벤트를 서드 파티 SDK에서 Google 모바일 광고 SDK로 전달할 수 있습니다. SampleCustomEventBanner 클래스는 SampleBannerAdDelegate 프로토콜을 구현하여 샘플 광고 네트워크에서 Google 모바일 광고 SDK로 콜백을 전달합니다.

맞춤 이벤트가 이러한 콜백을 최대한 많이 전달하여 앱이 Google 모바일 광고 SDK에서 상응하는 이벤트를 수신하도록 하는 것이 중요합니다. 다음은 콜백 사용의 예입니다.

Swift

func bannerWillLeaveApplication(_ banner: SampleBanner) {
  delegate?.reportClick()
}

Objective-C

- (void)bannerWillLeaveApplication:(SampleBanner *)banner {
  [_adEventDelegate reportClick];
}

배너 광고를 위한 맞춤 이벤트 구현이 완료되었습니다. 전체 예는 GitHub에서 확인할 수 있습니다. 이미 지원되는 광고 네트워크와 함께 사용하거나 맞춤 이벤트 배너 광고를 표시하도록 수정하여 사용할 수 있습니다.