Thiết lập SDK IMA

bắt đầu kiếm tiền từ nội dung video của bạn bằng quảng cáo.

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 tuân thủ VAST nào và quản lý việc phát quảng cáo trong ứng dụng của bạn. Với SDK phía máy khách IMA, bạn vẫn có 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 nằm phía trên 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 IMA SDK vào một ứng dụng trình phát video. Nếu bạn muốn 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ề phía máy khách IMA

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

  • IMAAdDisplayContainer: Một đối tượng vùng chứa chỉ định vị trí mà IMA hiển thị các phần tử 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ả Chế độ xem đang kích hoạtĐ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 một trình tải quảng cáo và có thể sử dụng lại trình tải này 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. Các yêu cầu về quảng cáo chỉ định URL cho thẻ quảng cáo VAST, cũng như các thông 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à lắng nghe 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ó những thông tin sau:

  • Xcode 13 trở lên
  • CocoaPods (ưu tiên), Trình quản lý gói Swift hoặc bản sao đã tải xuống của SDK IMA cho iOS

1. Tạo một 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

CocoaPods là một trình quản lý phần phụ thuộc cho các dự án Xcode và là phương thức được đề xuất để cài đặt IMA SDK. Để biết thêm thông tin về cách cài đặt hoặc sử dụng CocoaPods, hãy xem tài liệu về CocoaPods. Sau khi cài đặt CocoaPods, hãy làm theo hướng dẫn sau để cài đặt IMA SDK:

  1. Trong cùng thư mục với tệp BasicExample.xcodeproj, hãy tạo một tệp văn bản có tên là Podfile rồi thêm cấu hình sau:

    Objective-C

    source 'https://github.com/CocoaPods/Specs.git'  platform :ios, '12'  target "BasicExample" do   pod 'GoogleAds-IMA-iOS-SDK', '~> 3.26.1' end  

    Swift

    source 'https://github.com/CocoaPods/Specs.git'  platform :ios, '12'  target "BasicExample" do   pod 'GoogleAds-IMA-iOS-SDK', '~> 3.26.1' end  
  2. Từ thư mục chứa Podfile, hãy chạy pod install --repo-update.

  3. Xác minh rằng quá trình cài đặt đã thành công bằng cách mở tệp BasicExample.xcworkspace và xác nhận rằng tệp này chứa 2 dự án: BasicExamplePods (các phần phụ thuộc do CocoaPods cài đặt).

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

SDK Quảng cáo tương tác trên phương tiện truyền thông hỗ trợ Trình quản lý gói Swift kể từ phiên bản 3.18.4. Để 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 cho 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.

Sau 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 xem bài viết của Apple.

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

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

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 IMA SDK và không chứa phương thức nào để kích hoạt quá trình 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 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 chạy 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 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 chạy 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 SDK IMA:

    @import GoogleInteractiveMediaAds; 
  2. Tạo các biến cho các lớp IMAAdsLoader, IMAAVPlayerContentPlayheadIMAAdsManager đượ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 SDK IMA:

    import GoogleInteractiveMediaAds  
  2. Tạo các biến cho các lớp IMAAdsLoader, IMAAVPlayerContentPlayheadIMAAdsManager đượ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 vị trí phát nội dung và trình quan sát cuối luồng phát

Để phát quảng cáo trong lúc phát, SDK IMA 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 khi nào nội dung của bạn phát xong để SDK có thể hiển thị quảng cáo cuối video. Việc này được thực hiện bằng cách gọi phương thức contentComplete trên IMAAdsLoader, sử dụng AVPlayerItemDidPlayToEndTimeNotification.

Objective-C

Tạo phiên bản IMAAVPlayerContentPlayhead trong chế độ 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 đối tượng tiếp nhận dữ liệu kết thúc nội dung trong chế độ 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 chạy trình tải quảng cáo và đưa ra 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. Bạn có thể dùng 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ụ thể.

Theo phương pháp hay nhất, bạn chỉ nên duy trì một phiên bản IMAAdsLoader cho toàn bộ vòng đời của ứng dụng. Để đưa ra các yêu cầu quảng cáo bổ sung, 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ề SDK IMA.

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 một uỷ quyền trình tải quảng cáo

Trong một sự kiện tải thành công, IMAAdsLoader sẽ gọi phương thức adsLoadedWithData của uỷ quyền được chỉ định, truyền cho phương thức này một phiên bản của IMAAdsManager. Sau đó, bạn có thể khởi chạy trình quản lý quảng cáo để tải từng quảng cáo, như được xác định bằng phản hồi đối với 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 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 uỷ quyền riêng. IMAAdManagerDelegate có các phương thức để xử lý các sự kiện và lỗi quảng cáo, cũng như các phương thức để kích hoạt chế độ 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 chi tiết, 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 một trình xử lý cho lỗi quảng cáo. Nếu xảy ra lỗi, chẳng hạn 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 các sự kiện phát và tạm dừng

Hai phương thức uỷ nhiệm cuối cùng mà bạn cần triển khai được dùng để 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 được IMA SDK yêu cầu. Việc kích hoạt chế độ 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 xuất hiện.

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 bổ sung của SDK, hãy xem các hướng dẫn khác hoặc cá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à theo dõi ứng dụng để sử dụng IDFA.