네이티브 광고 고급형

시스템 정의 네이티브 광고 형식 표시

네이티브 광고가 로드되면 앱에서 GADAdLoaderDelegate 프로토콜 메시지 그러면 앱은 바로 표시할 필요는 없습니다. 시스템 정의 광고 형식을 보다 쉽게 표시할 수 있도록 SDK에서는 몇 가지 유용한 리소스를 배포합니다

GADNativeAdView

GADNativeAd의 경우 해당하는 '광고 보기'가 있습니다. 클래스: GADNativeAdView 이 광고 보기 클래스는 게시자가 광고를 표시하는 데 사용해야 하는 UIView입니다. 예를 들어 단일 GADNativeAdView는 단일 인스턴스를 표시할 수 있습니다. GADNativeAd 광고의 각 UIView 객체는 애셋은 해당 GADNativeAdView 객체의 하위 뷰여야 합니다.

예를 들어 UITableView에 광고를 표시했다면 셀 중 하나의 뷰 계층 구조는 다음과 같을 수 있습니다.

GADNativeAdView 클래스는 또한 등록에 사용되는 IBOutlets를 제공합니다. 각 애셋에 사용된 보기 및 GADNativeAd 객체 자체를 정의하는 것입니다. 이 방법으로 뷰를 등록하면 SDK가 자동으로 다음과 같은 작업을 처리합니다.

  • 클릭수 기록
  • 노출수 기록 (첫 픽셀이 화면에 표시되는 시점)
  • AdChoices 오버레이 표시

AdChoices 오버레이

간접 네이티브 광고( Ad Manager을(를) 통해 게재됨) 백업 광고, Ad Exchange 또는 애드센스)를 통해 AdChoices 오버레이는 생성합니다. 원하는 위치에 여유 공간을 남겨두세요. 모서리 AdChoices 로고가 자동으로 삽입되도록 할 수 있습니다. 또한 AdChoices 오버레이가 아이콘을 표시할 수 있는 콘텐츠에 배치되는지 쉽게 찾을 수 있습니다. 오버레이의 모양과 기능에 대한 자세한 내용은 프로그래매틱 네이티브 광고 구현 가이드라인을 따라야 합니다.

프로그래매틱 네이티브 광고의 광고 표시

프로그래매틱 네이티브 광고를 표시할 때 조회가 광고임을 나타냅니다. 이 페이지에서 정책 가이드라인을 확인하세요.

코드 예

동적으로 로드된 보기를 사용하여 네이티브 광고를 표시하는 방법을 살펴보겠습니다. xib 파일에서 추출됩니다. 이는 GADAdLoaders를 사용할 때 매우 유용한 접근 방식입니다. 여러 형식을 요청하도록 구성되어 있습니다.

UIViews 배치

첫 단계는 네이티브 광고 애셋을 표시할 UIViews를 배치하는 것입니다. 다른 태그를 생성할 때와 마찬가지로 인터페이스 빌더에서 이 작업을 수행할 수 있습니다. xib 파일에 추가합니다. 네이티브 광고 레이아웃은 다음과 같이 표시될 수 있습니다.

이미지 오른쪽 상단의 커스텀 클래스 값을 확인하세요. 설정값은

GADNativeAdView 이는 GADNativeAd를 표시하는 데 사용된 광고 보기 클래스입니다.

사용되는 GADMediaView의 맞춤 클래스도 설정해야 합니다. 광고의 동영상 또는 이미지가 표시됩니다.

보기를 배치했고 올바른 광고 보기 클래스를 만든 UIViews에 광고 보기의 애셋 아웃렛을 연결해야 합니다. 생성된 UIViews에 광고 보기의 확장 소재 아웃렛을 연결하는 방법은 다음과 같습니다. 다음을 참조하세요.

콘센트 패널에 GADNativeAdView의 콘센트가 연결되었습니다. 인터페이스 빌더에 배치된 UIViews입니다. 이를 통해 SDK는 어느 UIView가 어느 애셋을 표시하는지 알고 있습니다. 또한 이러한 아웃렛은 언젠가 사람들이 볼 수 있는 시야를 나타낸다는 점을 기억해야 합니다. 알 수 있습니다.

광고 표시

레이아웃이 완료되고 아웃렛이 연결된 후 다음 코드를 추가합니다. 을 추가해야 합니다.

Swift

// Mark: - GADNativeAdLoaderDelegate
func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) {
  print("Received native ad: \(nativeAd)")
  refreshAdButton.isEnabled = true
  // Create and place ad in view hierarchy.
  let nibView = Bundle.main.loadNibNamed("NativeAdView", owner: nil, options: nil)?.first
  guard let nativeAdView = nibView as? GADNativeAdView else {
    return
  }
  setAdView(nativeAdView)

  // Set ourselves as the native ad delegate to be notified of native ad events.
  nativeAd.delegate = self

  // Populate the native ad view with the native ad assets.
  // The headline and mediaContent are guaranteed to be present in every native ad.
  (nativeAdView.headlineView as? UILabel)?.text = nativeAd.headline
  nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent

  // This app uses a fixed width for the GADMediaView and changes its height to match the aspect
  // ratio of the media it displays.
  if let mediaView = nativeAdView.mediaView, nativeAd.mediaContent.aspectRatio > 0 {
    let heightConstraint = NSLayoutConstraint(
      item: mediaView,
      attribute: .height,
      relatedBy: .equal,
      toItem: mediaView,
      attribute: .width,
      multiplier: CGFloat(1 / nativeAd.mediaContent.aspectRatio),
      constant: 0)
    heightConstraint.isActive = true
  }

  // These assets are not guaranteed to be present. Check that they are before
  // showing or hiding them.
  (nativeAdView.bodyView as? UILabel)?.text = nativeAd.body
  nativeAdView.bodyView?.isHidden = nativeAd.body == nil

  (nativeAdView.callToActionView as? UIButton)?.setTitle(nativeAd.callToAction, for: .normal)
  nativeAdView.callToActionView?.isHidden = nativeAd.callToAction == nil

  (nativeAdView.iconView as? UIImageView)?.image = nativeAd.icon?.image
  nativeAdView.iconView?.isHidden = nativeAd.icon == nil

  (nativeAdView.starRatingView as? UIImageView)?.image = imageOfStars(
    fromStarRating: nativeAd.starRating)
  nativeAdView.starRatingView?.isHidden = nativeAd.starRating == nil

  (nativeAdView.storeView as? UILabel)?.text = nativeAd.store
  nativeAdView.storeView?.isHidden = nativeAd.store == nil

  (nativeAdView.priceView as? UILabel)?.text = nativeAd.price
  nativeAdView.priceView?.isHidden = nativeAd.price == nil

  (nativeAdView.advertiserView as? UILabel)?.text = nativeAd.advertiser
  nativeAdView.advertiserView?.isHidden = nativeAd.advertiser == nil

  // For the SDK to process touch events properly, user interaction should be disabled.
  nativeAdView.callToActionView?.isUserInteractionEnabled = false

  // Associate the native ad view with the native ad object. This is
  // required to make the ad clickable.
  // Note: this should always be done after populating the ad views.
  nativeAdView.nativeAd = nativeAd
}

SwiftUI

뷰 모델 만들기

네이티브 광고를 로드하고 네이티브 광고 데이터를 게시하는 뷰 모델 만들기 변경사항:

import GoogleMobileAds

class NativeAdViewModel: NSObject, ObservableObject, GADNativeAdLoaderDelegate {
  @Published var nativeAd: GADNativeAd?
  private var adLoader: GADAdLoader!

  func refreshAd() {
    adLoader = GADAdLoader(
      adUnitID: "ca-app-pub-3940256099942544/3986624511",
      // The UIViewController parameter is optional.
      rootViewController: nil,
      adTypes: [.native], options: nil)
    adLoader.delegate = self
    adLoader.load(GADRequest())
  }

  func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) {
    // Native ad data changes are published to its subscribers.
    self.nativeAd = nativeAd
    nativeAd.delegate = self
  }

  func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error) {
    print("\(adLoader) failed with error: \(error.localizedDescription)")
  }
}

UIViewRepresentable 만들기

만들기 UIViewRepresentable 드림 (GADNativeView에 대해) ViewModel에서 데이터 변경사항을 구독합니다. 클래스:

private struct NativeAdView: UIViewRepresentable {
  typealias UIViewType = GADNativeAdView

  // Observer to update the UIView when the native ad value changes.
  @ObservedObject var nativeViewModel: NativeAdViewModel

  func makeUIView(context: Context) -> GADNativeAdView {
    return
      Bundle.main.loadNibNamed(
        "NativeAdView",
        owner: nil,
        options: nil)?.first as! GADNativeAdView
  }

  func updateUIView(_ nativeAdView: GADNativeAdView, context: Context) {
    guard let nativeAd = nativeViewModel.nativeAd else { return }

    // Each UI property is configurable using your native ad.
    (nativeAdView.headlineView as? UILabel)?.text = nativeAd.headline

    nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent

    (nativeAdView.bodyView as? UILabel)?.text = nativeAd.body

    (nativeAdView.iconView as? UIImageView)?.image = nativeAd.icon?.image

    (nativeAdView.starRatingView as? UIImageView)?.image = imageOfStars(from: nativeAd.starRating)

    (nativeAdView.storeView as? UILabel)?.text = nativeAd.store

    (nativeAdView.priceView as? UILabel)?.text = nativeAd.price

    (nativeAdView.advertiserView as? UILabel)?.text = nativeAd.advertiser

    (nativeAdView.callToActionView as? UIButton)?.setTitle(nativeAd.callToAction, for: .normal)

    // For the SDK to process touch events properly, user interaction should be disabled.
    nativeAdView.callToActionView?.isUserInteractionEnabled = false

    // Associate the native ad view with the native ad object. This is required to make the ad
    // clickable.
    // Note: this should always be done after populating the ad views.
    nativeAdView.nativeAd = nativeAd
  }

뷰 계층 구조에 뷰 추가

다음 코드는 뷰에 UIViewRepresentable를 추가하는 방법을 보여줍니다. 계층 구조:

struct NativeContentView: View {
  // Single source of truth for the native ad data.
  @StateObject private var nativeViewModel = NativeAdViewModel()

  var body: some View {
    ScrollView {
      VStack(spacing: 20) {
        NativeAdView(nativeViewModel: nativeViewModel)  // Updates when the native ad data changes.
          .frame(minHeight: 300)  // minHeight determined from xib.

Objective-C

#pragma mark GADNativeAdLoaderDelegate implementation

- (void)adLoader:(GADAdLoader *)adLoader didReceiveNativeAd:(GADNativeAd *)nativeAd {
  NSLog(@"Received native ad: %@", nativeAd);
  self.refreshButton.enabled = YES;

  // Create and place ad in view hierarchy.
  GADNativeAdView *nativeAdView =
      [[NSBundle mainBundle] loadNibNamed:@"NativeAdView" owner:nil options:nil].firstObject;
  [self setAdView:nativeAdView];

  // Set the mediaContent on the GADMediaView to populate it with available
  // video/image asset.
  nativeAdView.mediaView.mediaContent = nativeAd.mediaContent;

  // Populate the native ad view with the native ad assets.
  // The headline is guaranteed to be present in every native ad.
  ((UILabel *)nativeAdView.headlineView).text = nativeAd.headline;

  // These assets are not guaranteed to be present. Check that they are before
  // showing or hiding them.
  ((UILabel *)nativeAdView.bodyView).text = nativeAd.body;
  nativeAdView.bodyView.hidden = nativeAd.body ? NO : YES;

  [((UIButton *)nativeAdView.callToActionView)setTitle:nativeAd.callToAction
                                                forState:UIControlStateNormal];
  nativeAdView.callToActionView.hidden = nativeAd.callToAction ? NO : YES;

    ((UIImageView *)nativeAdView.iconView).image = nativeAd.icon.image;
  nativeAdView.iconView.hidden = nativeAd.icon ? NO : YES;

  ((UIImageView *)nativeAdView.starRatingView).image = [self imageForStars:nativeAd.starRating];
  nativeAdView.starRatingView.hidden = nativeAd.starRating ? NO : YES;

  ((UILabel *)nativeAdView.storeView).text = nativeAd.store;
  nativeAdView.storeView.hidden = nativeAd.store ? NO : YES;

  ((UILabel *)nativeAdView.priceView).text = nativeAd.price;
  nativeAdView.priceView.hidden = nativeAd.price ? NO : YES;

  ((UILabel *)nativeAdView.advertiserView).text = nativeAd.advertiser;
  nativeAdView.advertiserView.hidden = nativeAd.advertiser ? NO : YES;

  // In order for the SDK to process touch events properly, user interaction
  // should be disabled.
  nativeAdView.callToActionView.userInteractionEnabled = NO;

  // Associate the native ad view with the native ad object. This is
  // required to make the ad clickable.
  nativeAdView.nativeAd = nativeAd;
}

GitHub의 전체 예

Swift, SwiftUI 및 Objective-C를 다운로드할 수 있습니다.

Swift 맞춤 렌더링 예시 SwiftUI 네이티브 광고 예시 Objective-C 맞춤 렌더링 예시

GADMediaView

이미지 및 동영상 애셋은 GADMediaView xib 파일에서 정의하거나 동적으로 생성할 수 있는 UIView입니다. 다음과 같이 GADNativeAdView의 뷰 계층 구조 내에 배치해야 합니다. 다른 애셋 보기를 사용할 수 있습니다.

모든 애셋 보기와 마찬가지로, 미디어 보기에는 관련 콘텐츠가 있어야 합니다. 채워집니다. 이것은 mediaContent 드림 숙박 시설(GADMediaView) 이 다음의 mediaContent 속성: GADNativeAd (으)로 전달될 수 있는 미디어 콘텐츠가 들어 있습니다. GADMediaView:

다음은 맞춤 렌더링 예시 (Swift | Objective-C) 를 사용하여 GADMediaView에 네이티브 광고 애셋을 채우는 방법을 GADNativeAdGADMediaContent:

Swift

nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent

Objective-C

nativeAdView.mediaView.mediaContent = nativeAd.mediaContent;

네이티브 광고 보기의 인터페이스 생성 도구 파일에 뷰 맞춤 클래스를 GADMediaView로 설정하고 mediaView 콘센트.

이미지 콘텐츠 모드 변경

GADMediaView 클래스는 UIView를 준수합니다. contentMode 속성을 사용하여 이미지를 표시할 수 있습니다. 이미지 크기를 조정하는 방식을 변경하려는 경우 GADMediaView인 경우 상응하는 UIViewContentMode GADMediaViewcontentMode 속성에 사용하세요.

예를 들어 이미지가 표시될 때 GADMediaView를 채우려는 경우입니다 (광고에 동영상):

Swift

nativeAdView.mediaView?.contentMode = .aspectFill

Objective-C

nativeAdView.mediaView.contentMode = UIViewContentModeAspectFill;

GADMediaContent

GADMediaContent 클래스는 네이티브 광고의 미디어 콘텐츠와 관련된 데이터를 보유하며, 이는 GADMediaView 클래스를 사용하여 표시됩니다. GADMediaView에서 설정된 경우 mediaContent 속성:

  • 사용할 수 있는 동영상 애셋은 버퍼링 후 GADMediaView 다음을 확인하여 동영상 애셋을 사용할 수 있는지 알 수 있습니다. hasVideoContent

  • 광고에 동영상 애셋이 없으면 mainImage 애셋이 다운로드됩니다. 대신 GADMediaView 내에 배치되었습니다.

를 통해 개인정보처리방침을 정의할 수 있습니다.

다음 단계

사용자 개인 정보 보호에 대해 자세히 알아보기