Thiết lập SDK IMA

Chọn nền tảng: HTML5 Android iOS tvOS

SDK IMA giúp bạn dễ dàng tích hợp quảng cáo đa phương tiện vào trang web và ứng dụng của mình. SDK IMA có thể yêu cầu quảng cáo từ bất kỳ máy chủ quảng cáo nào tuân thủ VAST và quản lý việc phát quảng cáo trong ứng dụng của bạn. Với SDK IMA phía máy khách, bạn có thể duy trì quyền kiểm soát việc phát video nội dung, trong khi SDK xử lý việc phát quảng cáo. Quảng cáo phát trong một trình phát video riêng biệt được đặt ở đầu trình phát video nội dung của ứng dụng.

Hướng dẫn này minh hoạ cách tích hợp SDK IMA vào một ứng dụng trình phát video. Để xem hoặc làm theo một mẫu tích hợp hoàn chỉnh, hãy tải BasicExample xuống từ GitHub.

Tổng quan về IMA phía máy khách

Việc triển khai IMA phía máy khách bao gồm 4 thành phần SDK chính mà hướng dẫn này minh hoạ:

  • IMAAdDisplayContainer: Một đối tượng vùng chứa chỉ định nơi IMA hiển thị các phần tử trên giao diện người dùng của quảng cáo và đo lường khả năng xem, bao gồm cả Active View và Đo lường mở.
  • IMAAdsLoader: Một đối tượng yêu cầu quảng cáo và xử lý các sự kiện từ phản hồi yêu cầu quảng cáo. Bạn chỉ nên tạo thực thể cho một trình tải quảng cáo, có thể sử dụng lại trong suốt thời gian hoạt động của ứng dụng.
  • IMAAdsRequest: Một đối tượng xác định yêu cầu quảng cáo. Yêu cầu quảng cáo chỉ định URL cho thẻ quảng cáo VAST, cũng như các tham số bổ sung, chẳng hạn như kích thước quảng cáo.
  • IMAAdsManager: Một đối tượng chứa phản hồi cho yêu cầu quảng cáo, kiểm soát việc phát quảng cáo và theo dõi các sự kiện quảng cáo do SDK kích hoạt.

Điều kiện tiên quyết

Trước khi bắt đầu, bạn cần có:

1. Tạo dự án Xcode mới

Trong Xcode, hãy tạo một dự án iOS mới bằng Objective-C hoặc Swift. Sử dụng BasicExample làm tên dự án.

2. Thêm IMA SDK vào dự án Xcode

Để cài đặt IMA SDK, hãy chọn một phương thức bạn muốn.

Nên dùng: Cài đặt SDK bằng Trình quản lý gói Swift

Interactive Media Ads SDK hỗ trợ Trình quản lý gói Swift phiên bản 3.18.4 trở lên. Để nhập gói Swift, hãy hoàn tất các bước sau:

  1. Trong Xcode, hãy cài đặt Gói Swift SDK IMA bằng cách chuyển đến File (Tệp) > Add Package Dependencies (Thêm phần phụ thuộc của gói)....

  2. Trong lời nhắc, hãy tìm kho lưu trữ GitHub của Gói Swift SDK IMA cho iOS: swift-package-manager-google-interactive-media-ads-ios.

  3. Chọn phiên bản của Gói Swift IMA SDK mà bạn muốn sử dụng. Đối với các dự án mới, bạn nên sử dụng Phiên bản lớn tiếp theo.

Khi bạn đã hoàn tất, Xcode sẽ phân giải các phần phụ thuộc của gói và tải các phần phụ thuộc đó xuống ở chế độ nền. Để biết thêm thông tin chi tiết về cách thêm các phần phụ thuộc của gói, hãy đọc bài viết của Apple.

Tải xuống và cài đặt SDK theo cách thủ công

Nếu bạn không muốn sử dụng Trình quản lý gói Swift, hãy tải xuống và thêm IMA SDK vào dự án theo cách thủ công.

3. Tạo trình phát video

Trước tiên, hãy triển khai một trình phát video. Ban đầu, trình phát này không sử dụng SDK IMA và không chứa bất kỳ phương thức nào để kích hoạt tính năng phát.

Objective-C

Nhập các phần phụ thuộc của trình phát:

#import "ViewController.h"

@import AVFoundation;

Thiết lập các biến của trình phát:

@interface ViewController () <IMAAdsLoaderDelegate, IMAAdsManagerDelegate>

/// Content video player.
@property(nonatomic, strong) AVPlayer *contentPlayer;

/// Play button.
@property(nonatomic, weak) IBOutlet UIButton *playButton;

/// UIView in which we will render our AVPlayer for content.
@property(nonatomic, weak) IBOutlet UIView *videoView;

Khởi động trình phát video khi khung hiển thị tải:

@implementation ViewController

// The content URL to play.
NSString *const kTestAppContentUrl_MP4 =
    @"https://storage.googleapis.com/gvabox/media/samples/stock.mp4";

// Ad tag
NSString *const kTestAppAdTagUrl = @"https://pubads.g.doubleclick.net/gampad/ads?"
  @"iu=/21775744923/external/single_ad_samples&sz=640x480&cust_params=sample_ct%3Dlinear&"
  @"ciu_szs=300x250%2C728x90&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&"
  @"correlator=";

- (void)viewDidLoad {
  [super viewDidLoad];

  self.playButton.layer.zPosition = MAXFLOAT;

  [self setupAdsLoader];
  [self setUpContentPlayer];
}

#pragma mark Content Player Setup

- (void)setUpContentPlayer {
  // Load AVPlayer with path to our content.
  NSURL *contentURL = [NSURL URLWithString:kTestAppContentUrl_MP4];
  self.contentPlayer = [AVPlayer playerWithURL:contentURL];

  // Create a player layer for the player.
  AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.contentPlayer];

  // Size, position, and display the AVPlayer.
  playerLayer.frame = self.videoView.layer.bounds;
  [self.videoView.layer addSublayer:playerLayer];

  // Set up our content playhead and contentComplete callback.
  self.contentPlayhead = [[IMAAVPlayerContentPlayhead alloc] initWithAVPlayer:self.contentPlayer];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(contentDidFinishPlaying:)
                                               name:AVPlayerItemDidPlayToEndTimeNotification
                                             object:self.contentPlayer.currentItem];
}

- (IBAction)onPlayButtonTouch:(id)sender {
  [self requestAds];
  self.playButton.hidden = YES;
}

Swift

Nhập các phần phụ thuộc của trình phát:

import AVFoundation

Thiết lập các biến của trình phát:

class PlayerContainerViewController: UIViewController, IMAAdsLoaderDelegate, IMAAdsManagerDelegate {
  static let contentURL = URL(
    string: "https://storage.googleapis.com/gvabox/media/samples/stock.mp4")!

  private var contentPlayer = AVPlayer(url: PlayerContainerViewController.contentURL)

  private lazy var playerLayer: AVPlayerLayer = {
    AVPlayerLayer(player: contentPlayer)
  }()

Khởi động trình phát video khi khung hiển thị tải:

private lazy var videoView: UIView = {
  let videoView = UIView()
  videoView.translatesAutoresizingMaskIntoConstraints = false
  view.addSubview(videoView)

  NSLayoutConstraint.activate([
    videoView.bottomAnchor.constraint(
      equalTo: view.safeAreaLayoutGuide.bottomAnchor),
    videoView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
    videoView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
    videoView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
  ])
  return videoView
}()

// MARK: - View controller lifecycle methods

override func viewDidLoad() {
  super.viewDidLoad()

  videoView.layer.addSublayer(playerLayer)
  adsLoader.delegate = self

  NotificationCenter.default.addObserver(
    self,
    selector: #selector(contentDidFinishPlaying(_:)),
    name: .AVPlayerItemDidPlayToEndTime,
    object: contentPlayer.currentItem)
}

override func viewDidAppear(_ animated: Bool) {
  super.viewDidAppear(animated)
  playerLayer.frame = videoView.layer.bounds
}

override func viewWillTransition(
  to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator
) {
  coordinator.animate { _ in
    // do nothing
  } completion: { _ in
    self.playerLayer.frame = self.videoView.layer.bounds
  }
}

// MARK: - Public methods

func playButtonPressed() {
  requestAds()
}

4. Nhập IMA SDK

Để nhập IMA SDK, hãy làm như sau:

Objective-C

  1. Nhập IMA SDK:

    @import GoogleInteractiveMediaAds;
    
  2. Tạo biến cho các lớp IMAAdsLoader, IMAAVPlayerContentPlayhead và IMAAdsManager được dùng trong ứng dụng:

    // SDK
    /// Entry point for the SDK. Used to make ad requests.
    @property(nonatomic, strong) IMAAdsLoader *adsLoader;
    
    /// Playhead used by the SDK to track content video progress and insert mid-rolls.
    @property(nonatomic, strong) IMAAVPlayerContentPlayhead *contentPlayhead;
    
    /// Main point of interaction with the SDK. Created by the SDK as the result of an ad request.
    @property(nonatomic, strong) IMAAdsManager *adsManager;
    

Swift

  1. Nhập IMA SDK:

    import GoogleInteractiveMediaAds
    
    
  2. Tạo biến cho các lớp IMAAdsLoader, IMAAVPlayerContentPlayhead và IMAAdsManager được dùng trong ứng dụng:

    static let adTagURLString =
      "https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/"
      + "single_ad_samples&sz=640x480&cust_params=sample_ct%3Dlinear&ciu_szs=300x250%2C728x90&"
      + "gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&correlator="
    
    private let adsLoader = IMAAdsLoader()
    private var adsManager: IMAAdsManager?
    
    private lazy var contentPlayhead: IMAAVPlayerContentPlayhead = {
      IMAAVPlayerContentPlayhead(avPlayer: contentPlayer)
    }()
    

5. Triển khai trình theo dõi đầu phát nội dung và trình quan sát kết thúc luồng

Để phát quảng cáo chèn giữa, IMA SDK cần theo dõi vị trí hiện tại của nội dung video. Để thực hiện việc này, hãy tạo một lớp triển khai IMAContentPlayhead. Nếu bạn đang sử dụng AVPlayer, như trong ví dụ này, SDK sẽ cung cấp lớp IMAAVPlayerContentPlayhead để thực hiện việc này cho bạn. Nếu không sử dụng AVPlayer, bạn cần triển khai IMAContentPlayhead trên một lớp của riêng mình.

Bạn cũng cần cho SDK biết thời điểm nội dung của bạn phát xong để SDK có thể hiển thị quảng cáo chèn sau. Thực hiện việc này bằng cách gọi phương thức contentComplete trên IMAAdsLoader, sử dụng AVPlayerItemDidPlayToEndTimeNotification.

Objective-C

Tạo thực thể IMAAVPlayerContentPlayhead trong phần thiết lập trình phát:

// Set up our content playhead and contentComplete callback.
self.contentPlayhead = [[IMAAVPlayerContentPlayhead alloc] initWithAVPlayer:self.contentPlayer];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(contentDidFinishPlaying:)
                                             name:AVPlayerItemDidPlayToEndTimeNotification
                                           object:self.contentPlayer.currentItem];

Tạo phương thức contentDidFinishPlaying() để gọi IMAAdsLoader.contentComplete() khi nội dung phát xong:

- (void)contentDidFinishPlaying:(NSNotification *)notification {
  // Make sure we don't call contentComplete as a result of an ad completing.
  if (notification.object == self.contentPlayer.currentItem) {
    [self.adsLoader contentComplete];
  }
}

Swift

Tạo trình quan sát nội dung đã kết thúc trong phần thiết lập trình phát:

NotificationCenter.default.addObserver(
  self,
  selector: #selector(contentDidFinishPlaying(_:)),
  name: .AVPlayerItemDidPlayToEndTime,
  object: contentPlayer.currentItem)

Tạo phương thức contentDidFinishPlaying() để gọi IMAAdsLoader.contentComplete() khi nội dung phát xong:

@objc func contentDidFinishPlaying(_ notification: Notification) {
  // Make sure we don't call contentComplete as a result of an ad completing.
  if notification.object as? AVPlayerItem == contentPlayer.currentItem {
    adsLoader.contentComplete()
  }
}

6. Khởi động trình tải quảng cáo và tạo yêu cầu quảng cáo

Để yêu cầu một nhóm quảng cáo, bạn cần tạo một thực thể IMAAdsLoader. Trình tải này xử lý các đối tượng IMAAdsRequest được liên kết với một URL thẻ quảng cáo được chỉ định.

Phương pháp hay nhất là chỉ duy trì một thực thể của IMAAdsLoader cho toàn bộ vòng đời của ứng dụng. Để tạo thêm yêu cầu quảng cáo, hãy tạo một đối tượng IMAAdsRequest mới nhưng sử dụng lại cùng một IMAAdsLoader. Để biết thêm thông tin, hãy xem Câu hỏi thường gặp về IMA SDK.

Objective-C

- (void)setupAdsLoader {
  self.adsLoader = [[IMAAdsLoader alloc] initWithSettings:nil];
  self.adsLoader.delegate = self;
}

- (void)requestAds {
  // Create an ad display container for ad rendering.
  IMAAdDisplayContainer *adDisplayContainer =
      [[IMAAdDisplayContainer alloc] initWithAdContainer:self.videoView
                                          viewController:self
                                          companionSlots:nil];
  // Create an ad request with our ad tag, display container, and optional user context.
  IMAAdsRequest *request = [[IMAAdsRequest alloc] initWithAdTagUrl:kTestAppAdTagUrl
                                                adDisplayContainer:adDisplayContainer
                                                   contentPlayhead:self.contentPlayhead
                                                       userContext:nil];
  [self.adsLoader requestAdsWithRequest:request];
}

Swift

private func requestAds() {
  // Create ad display container for ad rendering.
  let adDisplayContainer = IMAAdDisplayContainer(
    adContainer: videoView, viewController: self, companionSlots: nil)
  // Create an ad request with our ad tag, display container, and optional user context.
  let request = IMAAdsRequest(
    adTagUrl: PlayerContainerViewController.adTagURLString,
    adDisplayContainer: adDisplayContainer,
    contentPlayhead: contentPlayhead,
    userContext: nil)

  adsLoader.requestAds(with: request)
}

7. Thiết lập trình uỷ quyền trình tải quảng cáo

Khi sự kiện tải thành công, IMAAdsLoader sẽ gọi phương thức adsLoadedWithData của trình uỷ quyền được chỉ định, truyền cho trình uỷ quyền đó một thực thể của IMAAdsManager. Sau đó, bạn có thể khởi động Ad Manager. Trình quản lý này sẽ tải các quảng cáo riêng lẻ, như được xác định bằng phản hồi cho URL thẻ quảng cáo.

Ngoài ra, hãy nhớ xử lý mọi lỗi có thể xảy ra trong quá trình tải. Nếu quảng cáo không tải, hãy đảm bảo rằng quá trình phát nội dung nghe nhìn vẫn tiếp tục mà không có quảng cáo để không ảnh hưởng đến trải nghiệm của người dùng.

Objective-C

- (void)adsLoader:(IMAAdsLoader *)loader adsLoadedWithData:(IMAAdsLoadedData *)adsLoadedData {
  // Grab the instance of the IMAAdsManager and set ourselves as the delegate.
  self.adsManager = adsLoadedData.adsManager;
  self.adsManager.delegate = self;
  // Create ads rendering settings to tell the SDK to use the in-app browser.
  IMAAdsRenderingSettings *adsRenderingSettings = [[IMAAdsRenderingSettings alloc] init];
  adsRenderingSettings.linkOpenerPresentingController = self;
  // Initialize the ads manager.
  [self.adsManager initializeWithAdsRenderingSettings:adsRenderingSettings];
}

- (void)adsLoader:(IMAAdsLoader *)loader failedWithErrorData:(IMAAdLoadingErrorData *)adErrorData {
  // Something went wrong loading ads. Log the error and play the content.
  NSLog(@"Error loading ads: %@", adErrorData.adError.message);
  [self.contentPlayer play];
}

Swift

func adsLoader(_ loader: IMAAdsLoader, adsLoadedWith adsLoadedData: IMAAdsLoadedData) {
  // Grab the instance of the IMAAdsManager and set ourselves as the delegate.
  adsManager = adsLoadedData.adsManager
  adsManager?.delegate = self

  // Create ads rendering settings and tell the SDK to use the in-app browser.
  let adsRenderingSettings = IMAAdsRenderingSettings()
  adsRenderingSettings.linkOpenerPresentingController = self

  // Initialize the ads manager.
  adsManager?.initialize(with: adsRenderingSettings)
}

func adsLoader(_ loader: IMAAdsLoader, failedWith adErrorData: IMAAdLoadingErrorData) {
  if let message = adErrorData.adError.message {
    print("Error loading ads: \(message)")
  }
  contentPlayer.play()
}

8. Thiết lập người được uỷ quyền quản lý quảng cáo

Cuối cùng, để quản lý các sự kiện và thay đổi trạng thái, trình quản lý quảng cáo cần có một trình uỷ quyền riêng. IMAAdManagerDelegate có các phương thức để xử lý sự kiện và lỗi quảng cáo, cũng như các phương thức để kích hoạt tính năng phát và tạm dừng trên nội dung video của bạn.

Bắt đầu phát lại

Theo dõi sự kiện LOADED để bắt đầu phát nội dung và quảng cáo. Để biết thêm thông tin, hãy xem didReceiveAdEvent.

Objective-C

- (void)adsManager:(IMAAdsManager *)adsManager didReceiveAdEvent:(IMAAdEvent *)event {
  // When the SDK notified us that ads have been loaded, play them.
  if (event.type == kIMAAdEvent_LOADED) {
    [adsManager start];
  }
}

Swift

func adsManager(_ adsManager: IMAAdsManager, didReceive event: IMAAdEvent) {
  // When the SDK notifies us the ads have been loaded, play them.
  if event.type == IMAAdEventType.LOADED {
    adsManager.start()
  }
}

Xử lý lỗi

Thêm trình xử lý cho lỗi quảng cáo. Nếu xảy ra lỗi, như trong bước trước, hãy tiếp tục phát nội dung.

Objective-C

- (void)adsManager:(IMAAdsManager *)adsManager didReceiveAdError:(IMAAdError *)error {
  // Something went wrong with the ads manager after ads were loaded. Log the error and play the
  // content.
  NSLog(@"AdsManager error: %@", error.message);
  [self.contentPlayer play];
}

Swift

func adsManager(_ adsManager: IMAAdsManager, didReceive error: IMAAdError) {
  // Something went wrong with the ads manager after ads were loaded.
  // Log the error and play the content.
  if let message = error.message {
    print("AdsManager error: \(message)")
  }
  contentPlayer.play()
}

Theo dõi sự kiện phát và tạm dừng

Hai phương thức uỷ quyền cuối cùng mà bạn cần triển khai sẽ kích hoạt các sự kiện phát và tạm dừng trên nội dung video cơ bản khi IMA SDK yêu cầu. Việc kích hoạt tạm dừng và phát khi được yêu cầu sẽ giúp người dùng không bỏ lỡ các phần của nội dung video khi quảng cáo hiển thị.

Objective-C

- (void)adsManagerDidRequestContentPause:(IMAAdsManager *)adsManager {
  // The SDK is going to play ads, so pause the content.
  [self.contentPlayer pause];
}

- (void)adsManagerDidRequestContentResume:(IMAAdsManager *)adsManager {
  // The SDK is done playing ads (at least for now), so resume the content.
  [self.contentPlayer play];
}

Swift

func adsManagerDidRequestContentPause(_ adsManager: IMAAdsManager) {
  // The SDK is going to play ads, so pause the content.
  contentPlayer.pause()
}

func adsManagerDidRequestContentResume(_ adsManager: IMAAdsManager) {
  // The SDK is done playing ads (at least for now), so resume the content.
  contentPlayer.play()
}

Vậy là xong! Giờ đây, bạn đang yêu cầu và hiển thị quảng cáo bằng SDK IMA. Để tìm hiểu về các tính năng khác của SDK, hãy xem các hướng dẫn khác hoặc mẫu trên GitHub.

Các bước tiếp theo

Để tối đa hoá doanh thu từ quảng cáo trên nền tảng iOS, hãy yêu cầu quyền Minh bạch về việc theo dõi ứng dụng để sử dụng IDFA.