배너 광고

배너 광고는 앱 레이아웃의 일부를 차지하는 직사각형 광고입니다. 사용자가 앱과 상호작용하는 동안 배너 광고가 화면의 상단이나 하단에 앵커 형식으로 표시되거나 스크롤할 때 인라인 형식으로 콘텐츠와 함께 화면에 표시됩니다. 배너 광고는 일정 시간이 지나면 자동으로 새로고침될 수 있습니다. 자세한 내용은 배너 광고 개요를 참고하세요.

이 가이드에서는 지정한 광고 너비로 각 기기의 광고 크기를 최적화하여 실적을 극대화하는 앵커 적응형 배너 광고를 시작하는 방법을 설명합니다.

앵커 적응형 배너

앵커 적응형 배너 광고는 일반적인 고정 크기 광고가 아닌 고정된 가로세로 비율 광고입니다. 가로세로 비율은 업계 표준 320*50과 유사합니다. 사용 가능한 전체 너비를 지정하면 해당 너비에 맞는 높이로 광고가 반환됩니다. 최적의 높이는 동일한 기기의 요청에 따라 변경되지 않으며 광고를 새로고침할 때 주변 뷰를 이동할 필요가 없습니다.

기본 요건

항상 테스트 광고로 테스트

앱을 빌드하고 테스트할 때는 실제 프로덕션 광고 대신 테스트 광고를 사용하세요. 이렇게 하지 않으면 계정이 정지될 수 있습니다.

테스트 광고를 로드하는 가장 쉬운 방법은 다음과 같은 iOS 배너 테스트 전용 광고 단위 ID를 사용하는 것입니다. /6499/example/adaptive-banner

이 ID는 모든 요청에 대해 테스트 광고를 반환하도록 특별히 구성되었으며, 코딩, 테스트, 디버깅 중에 앱에서 자유롭게 사용할 수 있습니다. 앱을 게시하기 전에 이 ID를 자체 광고 단위 ID로 바꿔야 합니다.

모바일 광고 SDK의 테스트 광고가 작동하는 방식을 자세히 알아보려면 테스트 광고를 참고하세요.

GAMBannerView 만들기

배너 광고는 GAMBannerView 객체에 표시되므로 배너 광고를 통합하려면 먼저 GAMBannerView를 뷰 계층 구조에 포함해야 합니다. 이 작업은 일반적으로 프로그래매틱 방식으로 또는 인터페이스 생성 도구를 통해 진행됩니다.

프로그래매틱 방식

GAMBannerView는 직접 인스턴스화할 수도 있습니다. 다음은 화면의 안전 영역의 하단 중앙에 정렬된 GAMBannerView를 만드는 방법을 보여주는 예입니다.

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController {

  var bannerView: GAMBannerView!

  override func viewDidLoad() {
    super.viewDidLoad()
    
    let viewWidth = view.frame.inset(by: view.safeAreaInsets).width

    // Here the current interface orientation is used. Use
    // GADLandscapeAnchoredAdaptiveBannerAdSizeWithWidth or
    // GADPortraitAnchoredAdaptiveBannerAdSizeWithWidth if you prefer to load an ad of a
    // particular orientation,
    let adaptiveSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)
    bannerView = GAMBannerView(adSize: adaptiveSize)

    addBannerViewToView(bannerView)
  }

  func addBannerViewToView(_ bannerView: GAMBannerView) {
    bannerView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(bannerView)
    view.addConstraints(
      [NSLayoutConstraint(item: bannerView,
                          attribute: .bottom,
                          relatedBy: .equal,
                          toItem: view.safeAreaLayoutGuide,
                          attribute: .bottom,
                          multiplier: 1,
                          constant: 0),
       NSLayoutConstraint(item: bannerView,
                          attribute: .centerX,
                          relatedBy: .equal,
                          toItem: view,
                          attribute: .centerX,
                          multiplier: 1,
                          constant: 0)
      ])
   }
   
}

Objective-C

@import GoogleMobileAds;

@interface ViewController ()

@property(nonatomic, strong) GAMBannerView *bannerView;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  
  // Here safe area is taken into account, hence the view frame is used after the
  // view has been laid out.
  CGRect frame = UIEdgeInsetsInsetRect(self.view.frame, self.view.safeAreaInsets);
  CGFloat viewWidth = frame.size.width;

  // Here the current interface orientation is used. If the ad is being preloaded
  // for a future orientation change or different orientation, the function for the
  // relevant orientation should be used.
  GADAdSize adaptiveSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth);
  // In this case, we instantiate the banner with desired ad size.
  self.bannerView = [[GAMBannerView alloc] initWithAdSize:adaptiveSize];

  [self addBannerViewToView:self.bannerView];
}

- (void)addBannerViewToView:(UIView *)bannerView {
  bannerView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:bannerView];
  [self.view addConstraints:@[
    [NSLayoutConstraint constraintWithItem:bannerView
                               attribute:NSLayoutAttributeBottom
                               relatedBy:NSLayoutRelationEqual
                                  toItem:self.view.safeAreaLayoutGuide
                               attribute:NSLayoutAttributeBottom
                              multiplier:1
                                constant:0],
    [NSLayoutConstraint constraintWithItem:bannerView
                               attribute:NSLayoutAttributeCenterX
                               relatedBy:NSLayoutRelationEqual
                                  toItem:self.view
                               attribute:NSLayoutAttributeCenterX
                              multiplier:1
                                constant:0]
                                ]];
}
  
@end

이 경우에는 제공된 광고 크기가 보기 크기를 조정하기 위한 고유한 콘텐츠 크기를 배너에 제공하므로 너비 또는 높이 제약 조건을 지정하지 않습니다.

인터페이스 빌더

GAMBannerView는 스토리보드 또는 xib 파일에 추가할 수 있습니다. 이 방법을 사용할 때는 배너에 위치 제한만 추가해야 합니다. 예를 들어 화면 하단에 적응형 배너를 표시하는 경우 배너 뷰의 하단을 하단 레이아웃 가이드의 상단과 동일하게 설정하고 중앙 X를 슈퍼뷰의 중앙 X와 같게 설정합니다.

배너의 광고 크기는 계속해서 프로그래매틱 방식으로 설정됩니다.

Swift

  bannerView.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)

Objective-C

  self.bannerView.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth);

광고 로드

GAMBannerView가 배치되고 속성이 구성되었으면 광고를 로드하세요. 다음과 같이 GAMRequest 객체에서 loadRequest:를 호출하면 됩니다.

Swift

override func viewDidLoad() {
  super.viewDidLoad()
  ...
  
  //  Set the ad unit ID and view controller that contains the GAMBannerView.
  bannerView.adUnitID = "/6499/example/adaptive-banner"
  bannerView.rootViewController = self

  bannerView.load(GAMRequest())
}

Objective-C

-   (void)viewDidLoad {
  [super viewDidLoad];
  ...
  
  //  Set the ad unit ID and view controller that contains the GAMBannerView.
  self.bannerView.adUnitID = @"/6499/example/adaptive-banner";
  self.bannerView.rootViewController = self;

  [self.bannerView loadRequest:[GAMRequest request]];
}

GAMRequest 객체는 단일 광고 요청을 나타내며, 타겟팅 정보와 같은 속성을 포함합니다.

광고 단위가 새로고침되도록 이미 설정했다면 광고가 로드되지 않더라도 다른 광고를 명시적으로 요청하지 않아도 됩니다. Google 모바일 광고 SDK는 Ad Manager UI에서 지정한 새로고침 빈도를 사용합니다. 새로고침을 사용 설정하지 않았다면 새로 요청해야 합니다.

광고 이벤트

GADBannerViewDelegate를 사용하면 광고가 닫히거나 사용자가 앱을 종료하는 것과 같은 수명 주기 이벤트를 수신 대기할 수 있습니다.

배너 이벤트에 등록

배너 광고 이벤트에 등록하려면 GAMBannerViewdelegate 속성을 GADBannerViewDelegate 프로토콜을 구현하는 객체로 설정하세요. 일반적으로는 배너 광고를 구현하는 클래스가 대리자 클래스로도 작동하며, 이러한 경우 delegate 속성을 self로 설정할 수 있습니다.

Swift

import GoogleMobileAds
import UIKit

class ViewController: UIViewController, GADBannerViewDelegate {

  var bannerView: GAMBannerView!

  override func viewDidLoad() {
    super.viewDidLoad()
    ...
    bannerView.delegate = self
  }
}

Objective-C

@import GoogleMobileAds;

@interface ViewController () <GADBannerViewDelegate>

@property(nonatomic, strong) GAMBannerView *bannerView;

@end

@implementation ViewController

-   (void)viewDidLoad {
  [super viewDidLoad];
  ...
  self.bannerView.delegate = self;
}

배너 이벤트 구현

GADBannerViewDelegate의 각 메서드는 선택사항으로 표시되므로 원하는 메서드만 구현하면 됩니다. 이 예에서는 각 메서드를 구현하고 콘솔에 메시지를 기록합니다.

Swift

func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
  print("bannerViewDidReceiveAd")
}

func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
  print("bannerView:didFailToReceiveAdWithError: \(error.localizedDescription)")
}

func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
  print("bannerViewDidRecordImpression")
}

func bannerViewWillPresentScreen(_ bannerView: GADBannerView) {
  print("bannerViewWillPresentScreen")
}

func bannerViewWillDismissScreen(_ bannerView: GADBannerView) {
  print("bannerViewWillDIsmissScreen")
}

func bannerViewDidDismissScreen(_ bannerView: GADBannerView) {
  print("bannerViewDidDismissScreen")
}

Objective-C

-   (void)bannerViewDidReceiveAd:(GADBannerView *)bannerView {
  NSLog(@"bannerViewDidReceiveAd");
}

-   (void)bannerView:(GADBannerView *)bannerView didFailToReceiveAdWithError:(NSError *)error {
  NSLog(@"bannerView:didFailToReceiveAdWithError: %@", [error localizedDescription]);
}

-   (void)bannerViewDidRecordImpression:(GADBannerView *)bannerView {
  NSLog(@"bannerViewDidRecordImpression");
}

-   (void)bannerViewWillPresentScreen:(GADBannerView *)bannerView {
  NSLog(@"bannerViewWillPresentScreen");
}

-   (void)bannerViewWillDismissScreen:(GADBannerView *)bannerView {
  NSLog(@"bannerViewWillDismissScreen");
}

-   (void)bannerViewDidDismissScreen:(GADBannerView *)bannerView {
  NSLog(@"bannerViewDidDismissScreen");
}

iOS API 데모 앱의 배너 대리자 메서드 구현을 보려면 광고 대리자 예를 참고하세요.

Swift Objective-C

사용 사례

다음은 이러한 광고 이벤트 메서드의 사용 사례입니다.

광고가 수신된 후 뷰 계층 구조에 배너 추가

광고가 수신될 때까지 GAMBannerView를 뷰 계층 구조에 추가하지 않는 것이 좋습니다. bannerViewDidReceiveAd: 이벤트를 수신 대기하면 됩니다.

Swift

func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
  // Add banner to view and add constraints as above.
  addBannerViewToView(bannerView)
}

Objective-C

-   (void)bannerViewDidReceiveAd:(GAMBannerView *)bannerView {
  // Add bannerView to view and add constraints as above.
  [self addBannerViewToView:self.bannerView];
}

배너 광고 애니메이션

다음 예와 같이 반환된 배너 광고에 bannerViewDidReceiveAd: 이벤트를 사용하여 애니메이션을 적용할 수도 있습니다.

Swift

func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
  bannerView.alpha = 0
  UIView.animate(withDuration: 1, animations: {
    bannerView.alpha = 1
  })
}

Objective-C

-   (void)bannerViewDidReceiveAd:(GAMBannerView *)bannerView {
  bannerView.alpha = 0;
  [UIView animateWithDuration:1.0 animations:^{
    bannerView.alpha = 1;
  }];
}

앱 일시중지 및 다시 시작

GADBannerViewDelegate 프로토콜에는 클릭으로 인해 오버레이가 표시되거나 닫히는 시점과 같은 이벤트를 알리는 메서드가 있습니다. 이러한 이벤트가 광고로 인한 것인지를 추적하려면 이러한 GADBannerViewDelegate 메서드에 등록하세요.

광고 클릭에서 발생하는 것뿐만 아니라 모든 유형의 오버레이 표시나 외부 브라우저 호출을 포착하려면 앱이 UIViewController 또는 UIApplication에서 상응하는 메서드를 수신 대기하는 것이 좋습니다. 다음 표에는 GADBannerViewDelegate 메서드와 동시에 호출되는 iOS 메서드가 나와 있습니다.

GADBannerViewDelegate 메서드 iOS 메서드
bannerViewWillPresentScreen: UIViewController의 viewWillDisappear:
bannerViewWillDismissScreen: UIViewController의 viewWillAppear:
bannerViewDidDismissScreen: UIViewController의 viewDidAppear:

수동 노출수 집계

노출을 기록해야 하는 특별한 조건이 있는 경우 수동으로 Ad Manager에 노출 핑을 보낼 수 있습니다. 광고를 로드하기 전에 수동 노출을 위한 GAMBannerView를 먼저 사용 설정하면 됩니다.

Swift

bannerView.enableManualImpressions = true

Objective-C

self.bannerView.enableManualImpressions = YES;

광고가 반환되어 화면에 표시된 것이 확인되면 수동으로 노출을 실행할 수 있습니다.

Swift

bannerView.recordImpression()

Objective-C

[self.bannerView recordImpression];

앱 이벤트

앱 이벤트를 사용하면 앱 코드에 메시지를 보낼 수 있는 광고를 만들 수 있습니다. 그러면 앱에서 이러한 메시지를 기반으로 작업을 실행할 수 있습니다.

GADAppEventDelegate를 사용하여 Ad Manager 관련 앱 이벤트를 수신할 수 있습니다. 이러한 이벤트는 GADBannerViewDelegate 객체의 bannerViewDidReceiveAd:가 호출되기 전을 포함해 광고 수명 주기 동안 언제든지 발생할 수 있습니다.

Swift

// Implement your app event within this method. The delegate will be
// notified when the SDK receives an app event message from the ad.

// Called when the banner receives an app event.
optional public func bannerView(_ banner: GAMBannerView,
    didReceiveAppEvent name: String, withInfo info: String?)

Objective-C

// Implement your app event within this method. The delegate will be
// notified when the SDK receives an app event message from the ad.

@optional
// Called when the banner receives an app event.
-   (void)bannerView:(GAMBannerView *)banner
    didReceiveAppEvent:(NSString *)name
              withInfo:(NSString *)info;

앱 이벤트 메서드는 뷰 컨트롤러에서 구현할 수 있습니다.

Swift

import GoogleMobileAds

class ViewController: UIViewController, GADAppEventDelegate {
}

Objective-C

@import GoogleMobileAds;

@interface ViewController : UIViewController <GADAppEventDelegate> {
}

@end

광고를 요청하기 전에 appEventDelegate 속성을 사용하여 대리자를 설정해야 합니다.

Swift

bannerView.appEventDelegate = self

Objective-C

self.bannerView.appEventDelegate = self;

다음은 앱 이벤트를 통해 색상을 지정하여 앱의 배경색을 변경하는 방법의 예입니다.

Swift

func bannerView(_ banner: GAMBannerView, didReceiveAppEvent name: String,
    withInfo info: String?) {
  if name == "color" {
    guard let info = info else { return }
    switch info {
    case "green":
      // Set background color to green.
      view.backgroundColor = UIColor.green
    case "blue":
      // Set background color to blue.
      view.backgroundColor = UIColor.blue
    default:
      // Set background color to black.
      view.backgroundColor = UIColor.black
    }
  }
}

Objective-C

-   (void)bannerView:(GAMBannerView *)banner
    didReceiveAppEvent:(NSString *)name
              withInfo:(NSString *)info {
  if ([name isEqual:@"color"]) {
    if ([info isEqual:@"green"]) {
      // Set background color to green.
      self.view.backgroundColor = [UIColor greenColor];
    } else if ([info isEqual:@"blue"]) {
      // Set background color to blue.
      self.view.backgroundColor = [UIColor blueColor];
    } else
      // Set background color to black.
      self.view.backgroundColor = [UIColor blackColor];
    }
  }
}

다음은 색상 앱 이벤트 메시지를 appEventDelegate에 보내는 광고 소재입니다.

<html>
<head>
  <script src="//www.gstatic.com/afma/api/v1/google_mobile_app_ads.js"></script>
  <script>
    document.addEventListener("DOMContentLoaded", function() {
      // Send a color=green event when ad loads.
      admob.events.dispatchAppEvent("color", "green");

      document.getElementById("ad").addEventListener("click", function() {
        // Send a color=blue event when ad is clicked.
        admob.events.dispatchAppEvent("color", "blue");
      });
    });
  </script>
  <style>
    #ad {
      width: 320px;
      height: 50px;
      top: 0px;
      left: 0px;
      font-size: 24pt;
      font-weight: bold;
      position: absolute;
      background: black;
      color: white;
      text-align: center;
    }
  </style>
</head>
<body>
  <div id="ad">Carpe diem!</div>
</body>
</html>

iOS API 데모 앱에서 앱 이벤트를 구현하려면 Ad Manager 앱 이벤트 예시를 참고하세요.

Swift Objective-C

추가 리소스

GitHub의 예

다음 단계

접을 수 있는 배너

접을 수 있는 배너 광고는 처음에 큰 오버레이로 표시되는 배너 광고로, 광고를 더 작은 크기로 접을 수 있는 버튼이 있습니다. 성능을 더욱 최적화하려면 이 도구를 사용해 보세요. 자세한 내용은 접을 수 있는 배너 광고를 참조하세요.

인라인 적응형 배너

인라인 적응형 배너는 앵커 적응형 배너에 비해 더 크고 더 긴 배너입니다. 이 배너는 높이가 가변적이며 기기 화면 높이만큼 높을 수도 있습니다. 스크롤 가능한 콘텐츠에 배너 광고를 게재하는 앱의 경우 앵커 적응형 배너 광고보다 인라인 적응형 배너가 권장됩니다. 자세한 내용은 인라인 적응형 배너를 참고하세요.

다른 주제 살펴보기