IMA SDK 可讓您輕鬆將多媒體廣告整合至您的網站和應用程式。IMA SDK 可以 向任何 與 VAST 相容的廣告伺服器,並管理您應用程式中的廣告播放方式。使用 IMA 用戶端 SDK 您能掌控內容影片播放,而 SDK 會處理廣告播放。廣告在 獨立影片播放器位於應用程式內容影片播放器上方。
本指南說明如何將 IMA SDK 整合到簡易的影片播放器中 應用程式。如果您要檢視或繼續完成樣本 請先下載 BasicExample: GitHub。
IMA 用戶端總覽
導入 IMA 用戶端需要四個主要 SDK 元件, 如本指南所示:
IMAAdDisplayContainer
: 廣告顯示位置的容器物件。IMAAdsLoader
: 這個物件會請求廣告,以及處理廣告請求回應中的事件。除了 將一個廣告載入器執行個體化,以便在應用程式生命週期中重複使用。IMAAdsRequest
: 定義廣告請求的物件。廣告請求會指定 VAST 廣告代碼的網址,以及 額外參數,例如廣告尺寸。IMAAdsManager
: 包含回應廣告請求、控制廣告播放以及監聽廣告的物件 SDK 觸發的事件。
必要條件
開始之前,請先備妥以下項目:
- Xcode 13 以上版本
- CocoaPods (建議)、Swift 套件管理員或 下載的 IMA SDK for iOS
1. 建立新的 Xcode 專案
在 Xcode 中,使用 Objective-C 或 Swift 建立新的 iOS 專案。使用 BasicExample 做為專案名稱。
2. 在 Xcode 專案中加入 IMA SDK
使用 CocoaPods 安裝 SDK (建議做法)
CocoaPods 是 Xcode 專案的依附元件管理工具,建議使用 方法。進一步瞭解如何安裝或使用 CocoaPods,請參閱 CocoaPods 說明文件。當您 已安裝 CocoaPods,請按照下列操作說明安裝 IMA SDK:
在與 BasicExample.xcodeproj 檔案相同的目錄中,建立文字 檔案,並新增以下設定:
source 'https://github.com/CocoaPods/Specs.git' platform :ios, '14' target "BasicExample" do pod 'GoogleAds-IMA-iOS-SDK', '~> 3.23.0' end
從包含 Podfile 的目錄,執行
pod install --repo-update
開啟 BasicExample.xcworkspace 檔案,並確認該檔案包含兩個專案: BasicExample 和 Pod (由 CocoaPods 安裝的依附元件)。
使用 Swift Package Manager 安裝 SDK
互動式媒體廣告 SDK 支援 Swift 套件 Manager,從 3.18.4 版開始。跟著 如何匯入 Swift 套件。
在 Xcode 中,前往 檔案 >新增套件...。
在隨即顯示的提示中,搜尋 IMA SDK Swift 套件 GitHub 存放區:
https://github.com/googleads/swift-package-manager-google-interactive-media-ads-ios
選取您要使用的 IMA SDK Swift 套件版本。 如要建立新專案,建議您使用直到下一個主要版本。
完成後,Xcode 會解析套件依附元件 在背景中下載這些檔案進一步瞭解如何新增套件 依附元件,請參閱 Apple 的文章。
手動下載並安裝 SDK
如果您不想使用 Swift Package Manager 或 CocoaPods,可以下載 IMA SDK 並 手動將其加入專案中。
3. 建立簡易影片播放器
首先,導入基本影片播放器。一開始,此播放器並未使用 IMA SDK,且尚未包含任何觸發播放的方法。
ViewController.m
Objective-C
#import "ViewController.h" #import <AVKit/AVKit.h> NSString *const kContentURLString = @"https://storage.googleapis.com/interactive-media-ads/media/stock.mp4"; @interface ViewController () @property(nonatomic) AVPlayerViewController *contentPlayerViewController; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = UIColor.blackColor; [self setupContentPlayer]; } - (void)setupContentPlayer { // Create a content video player. NSURL *contentURL = [NSURL URLWithString:kContentURLString]; AVPlayer *player = [AVPlayer playerWithURL:contentURL]; self.contentPlayerViewController = [[AVPlayerViewController alloc] init]; self.contentPlayerViewController.player = player; self.contentPlayerViewController.view.frame = self.view.bounds; // Attach content video player to view hierarchy. [self showContentPlayer]; } // Add the content video player as a child view controller. - (void)showContentPlayer { [self addChildViewController:self.contentPlayerViewController]; self.contentPlayerViewController.view.frame = self.view.bounds; [self.view insertSubview:self.contentPlayerViewController.view atIndex:0]; [self.contentPlayerViewController didMoveToParentViewController:self]; } // Remove and detach the content video player. - (void)hideContentPlayer { // The whole controller needs to be detached so that it doesn't capture events from the remote. [self.contentPlayerViewController willMoveToParentViewController:nil]; [self.contentPlayerViewController.view removeFromSuperview]; [self.contentPlayerViewController removeFromParentViewController]; } @end
Swift
import AVFoundation import UIKit class ViewController: UIViewController { static let ContentURLString = "https://storage.googleapis.com/interactive-media-ads/media/stock.mp4" var playerViewController: AVPlayerViewController! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.black setUpContentPlayer() } func setUpContentPlayer() { // Load AVPlayer with path to your content. let contentURL = URL(string: ViewController.ContentURLString) let player = AVPlayer(url: contentURL) playerViewController = AVPlayerViewController() playerViewController.player = player showContentPlayer() } func showContentPlayer() { self.addChild(playerViewController) playerViewController.view.frame = self.view.bounds self.view.insertSubview(playerViewController.view, at: 0) playerViewController.didMove(toParent:self) } func hideContentPlayer() { // The whole controller needs to be detached so that it doesn't capture // events from the remote. playerViewController.willMove(toParent:nil) playerViewController.view.removeFromSuperview() playerViewController.removeFromParent() } }
4. 匯入 IMA SDK
接下來,使用現有的匯入陳述式加入 IMA 架構 匯入。
ViewController.m
Objective-C
#import "ViewController.h" #import <AVKit/AVKit.h> #import <GoogleInteractiveMediaAds/GoogleInteractiveMediaAds.h> NSString *const kContentURLString = @"https://storage.googleapis.com/interactive-media-ads/media/stock.mp4";
Swift
import AVFoundation import GoogleInteractiveMediaAds import UIKit class ViewController: UIViewController { static let ContentURLString = "https://storage.googleapis.com/interactive-media-ads/media/stock.mp4"
5. 實作內容播放頭追蹤程式和串流結束觀察器
如要播放片中廣告,IMA SDK 必須追蹤目前的位置
三分之一的畫面方法是建立可實作
IMAContentPlayhead
。如以下範例所示,如果您使用 AVPlayer
SDK 提供的 IMAAVPlayerContentPlayhead
類別可以為您執行此操作。
如果您沒有使用 AVPlayer
,就必須在IMAContentPlayhead
和您自己建立的課程
您也需要讓 SDK 知道內容播放完畢,
顯示片尾廣告。方法是呼叫 contentComplete
IMAAdsLoader
,使用 AVPlayerItemDidPlayToEndTimeNotification
。
ViewController.m
Objective-C
... @interface ViewController () @property(nonatomic) IMAAVPlayerContentPlayhead *contentPlayhead; @property(nonatomic) AVPlayerViewController *contentPlayerViewController; @end ... - (void)setupContentPlayer { // Create a content video player. NSURL *contentURL = [NSURL URLWithString:kContentURLString]; AVPlayer *player = [AVPlayer playerWithURL:contentURL]; self.contentPlayerViewController = [[AVPlayerViewController alloc] init]; self.contentPlayerViewController.player = player; self.contentPlayerViewController.view.frame = self.view.bounds; self.contentPlayhead = [[IMAAVPlayerContentPlayhead alloc] initWithAVPlayer:self.contentPlayerViewController.player]; // Track end of content. AVPlayerItem *contentPlayerItem = self.contentPlayerViewController.player.currentItem; [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(contentDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:contentPlayerItem]; // Attach content video player to view hierarchy. [self showContentPlayer]; } ... - (void)contentDidFinishPlaying:(NSNotification *)notification {} - (void)dealloc { [NSNotificationCenter.defaultCenter removeObserver:self]; } @end
Swift
... class ViewController: UIViewController { static let ContentURLString = "https://storage.googleapis.com/interactive-media-ads/media/stock.mp4" var contentPlayhead: IMAAVPlayerContentPlayhead? var playerViewController: AVPlayerViewController! deinit { NotificationCenter.default.removeObserver(self) } ... func setUpContentPlayer() { // Load AVPlayer with path to your content. let contentURL! = URL(string: ViewController.ContentURLString) let player = AVPlayer(url: contentURL) playerViewController = AVPlayerViewController() playerViewController.player = player // Set up your content playhead and contentComplete callback. contentPlayhead = IMAAVPlayerContentPlayhead(avPlayer: player) NotificationCenter.default.addObserver( self, selector: #selector(ViewController.contentDidFinishPlaying(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem) showContentPlayer() } ... @objc func contentDidFinishPlaying(_ notification: Notification) { adsLoader.contentComplete() } }
6. 初始化廣告載入器並發出廣告請求
您必須建立 IMAAdsLoader
例項,才能要求一組廣告。
這個載入器可用來處理與IMAAdsRequest
指定的廣告代碼網址。
最佳做法是,在整個 IMAAdsLoader
中只維護一個 執行個體
生命週期的任何階段如要提出更多廣告請求,請建立新的
IMAAdsRequest
物件,但重複使用相同的 IMAAdsLoader
。如要
請參閱 IMA SDK 常見問題。
ViewController.m
Objective-C
... NSString *const kContentURLString = @"https://storage.googleapis.com/interactive-media-ads/media/stock.mp4"; NSString *const kAdTagURLString = @"https://pubads.g.doubleclick.net/gampad/ads?" @"iu=/21775744923/external/vmap_ad_samples&sz=640x480&" @"cust_params=sample_ar%3Dpremidpostlongpod&" @"ciu_szs=300x250&gdfp_req=1&ad_rule=1&output=vmap&unviewed_position_start=1&" @"env=vp&impl=s&cmsid=496&vid=short_onecue&correlator="; @interface ViewController () @property(nonatomic) IMAAdsLoader *adsLoader; @property(nonatomic) IMAAVPlayerContentPlayhead *contentPlayhead; @property(nonatomic) AVPlayerViewController *contentPlayerViewController; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = UIColor.blackColor; [self setupContentPlayer]; [self setupAdsLoader]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [self requestAds]; } - (void)setupAdsLoader { self.adsLoader = [[IMAAdsLoader alloc] init]; } - (void)requestAds { // Pass the main view as the container for ad display. IMAAdDisplayContainer *adDisplayContainer = [[IMAAdDisplayContainer alloc] initWithAdContainer:self.view]; IMAAdsRequest *request = [[IMAAdsRequest alloc] initWithAdTagUrl:kAdTagURLString adDisplayContainer:adDisplayContainer contentPlayhead:self.contentPlayhead userContext:nil]; [self.adsLoader requestAdsWithRequest:request]; } ... - (void)contentDidFinishPlaying:(NSNotification *)notification { // Notify the SDK that the postrolls should be played. [self.adsLoader contentComplete]; } ... @end
Swift
... class ViewController: UIViewController { static let ContentURLString = "https://storage.googleapis.com/interactive-media-ads/media/stock.mp4" 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&impl=s&correlator=" var adsLoader: IMAAdsLoader! var contentPlayhead: IMAAVPlayerContentPlayhead? var playerViewController: AVPlayerViewController! ... override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.black setUpContentPlayer() setUpAdsLoader() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) requestAds() } ... func setUpAdsLoader() { adsLoader = IMAAdsLoader(settings: nil) } func requestAds() { // Create ad display container for ad rendering. let adDisplayContainer = IMAAdDisplayContainer(adContainer: self.view) // Create an ad request with our ad tag, display container, and optional user context. let request = IMAAdsRequest( adTagUrl: ViewController.AdTagURLString, adDisplayContainer: adDisplayContainer, contentPlayhead: contentPlayhead, userContext: nil) adsLoader.requestAds(with: request) } @objc func contentDidFinishPlaying(_ notification: Notification) { adsLoader.contentComplete() } }
7. 設定廣告載入器委派
當載入事件成功時,IMAAdsLoader
會呼叫 adsLoadedWithData
方法並向其傳遞 IMAAdsManager
的例項。個人中心
然後初始化廣告管理系統,並依定義載入個別廣告
。
另外,請務必處理載入期間可能發生的所有錯誤 上傳資料集之後,您可以運用 AutoML 自動完成部分資料準備工作如果未載入廣告,請確認媒體播放作業持續, 以免干擾使用者體驗。
ViewController.m
Objective-C
... @interface ViewController () <IMAAdsLoaderDelegate> @property(nonatomic) IMAAdsLoader *adsLoader; @property(nonatomic) IMAAdsManager *adsManager; @property(nonatomic) IMAAVPlayerContentPlayhead *contentPlayhead; @property(nonatomic) AVPlayerViewController *contentPlayerViewController; @end @implementation ViewController ... - (void)setupAdsLoader { self.adsLoader = [[IMAAdsLoader alloc] init]; self.adsLoader.delegate = self; } ... #pragma mark - IMAAdsLoaderDelegate - (void)adsLoader:(IMAAdsLoader *)loader adsLoadedWithData:(IMAAdsLoadedData *)adsLoadedData { // Initialize and listen to the ads manager loaded for this request. self.adsManager = adsLoadedData.adsManager; [self.adsManager initializeWithAdsRenderingSettings:nil]; } - (void)adsLoader:(IMAAdsLoader *)loader failedWithErrorData:(IMAAdLoadingErrorData *)adErrorData { // Fall back to playing content. NSLog(@"Error loading ads: %@", adErrorData.adError.message); [self.contentPlayerViewController.player play]; } @end
Swift
... class ViewController: UIViewController, IMAAdsLoaderDelegate { ... var adsLoader: IMAAdsLoader! var adsManager: IMAAdsManager! var contentPlayhead: IMAAVPlayerContentPlayhead? var playerViewController: AVPlayerViewController! ... func setUpAdsLoader() { adsLoader = IMAAdsLoader(settings: nil) adsLoader.delegate = self } ... // MARK: - IMAAdsLoaderDelegate func adsLoader(_ loader: IMAAdsLoader!, adsLoadedWith adsLoadedData: IMAAdsLoadedData!) { adsManager = adsLoadedData.adsManager adsManager.initialize(with: nil) } func adsLoader(_ loader: IMAAdsLoader!, failedWith adErrorData: IMAAdLoadingErrorData!) { print("Error loading ads: " + adErrorData.adError.message) showContentPlayer() playerViewController.player?.play() } }
8. 設定廣告管理工具委派代表
最後,如要管理事件和狀態變更,必須指派
基礎架構IMAAdManagerDelegate
具有處理廣告事件和錯誤的方法。
以及觸發播放和暫停影片內容的方法
開始播放
didReceiveAdEvent
方法可處理許多事件,
不過在這個基本範例中,只要監聽 LOADED
事件來告知廣告
管理員開始播放內容和廣告。
ViewController.m
Objective-C
@interface ViewController () <IMAAdsLoaderDelegate, IMAAdsManagerDelegate> ... - (void)adsLoader:(IMAAdsLoader *)loader adsLoadedWithData:(IMAAdsLoadedData *)adsLoadedData { // Initialize and listen to the ads manager loaded for this request. self.adsManager = adsLoadedData.adsManager; self.adsManager.delegate = self; [self.adsManager initializeWithAdsRenderingSettings:nil]; } ... #pragma mark - IMAAdsManagerDelegate - (void)adsManager:(IMAAdsManager *)adsManager didReceiveAdEvent:(IMAAdEvent *)event { // Play each ad once it has loaded. if (event.type == kIMAAdEvent_LOADED) { [adsManager start]; } } ...
Swift
... class ViewController: UIViewController, IMAAdsLoaderDelegate, IMAAdsManagerDelegate { ... func adsLoader(_ loader: IMAAdsLoader!, adsLoadedWith adsLoadedData: IMAAdsLoadedData!) { // Grab the instance of the IMAAdsManager and set yourself as the delegate. adsManager = adsLoadedData.adsManager adsManager.delegate = self adsManager.initialize(with: nil) } ... // MARK: - IMAAdsManagerDelegate func adsManager(_ adsManager: IMAAdsManager!, didReceive event: IMAAdEvent!) { // Play each ad once it has been loaded if event.type == IMAAdEventType.LOADED { adsManager.start() } } ...
處理錯誤
您也可以在廣告錯誤中加入處理常式,如果發生錯誤 (例如先前的 步驟可繼續播放內容
ViewController.m
Objective-C
... - (void)adsManager:(IMAAdsManager *)adsManager didReceiveAdError:(IMAAdError *)error { // Fall back to playing content. NSLog(@"AdsManager error: %@", error.message); [self showContentPlayer]; [self.contentPlayerViewController.player play]; }</span> @end
Swift
... func adsManager(_ adsManager: IMAAdsManager!, didReceive error: IMAAdError!) { // Fall back to playing content print("AdsManager error: " + error.message) showContentPlayer() playerViewController.player?.play() }
觸發播放和暫停事件
您需要實作的最後兩個委派方法會用於觸發播放程序,以及 暫停事件 (在 IMA SDK 請求時)。 收到請求時觸發暫停和播放,可避免使用者缺漏部分資訊 會隨著廣告顯示
ViewController.m
Objective-C
... - (void)adsManagerDidRequestContentPause:(IMAAdsManager *)adsManager { // Pause the content for the SDK to play ads. [self.contentPlayerViewController.player pause]; [self hideContentPlayer]; } - (void)adsManagerDidRequestContentResume:(IMAAdsManager *)adsManager { // Resume the content since the SDK is done playing ads (at least for now). [self showContentPlayer]; [self.contentPlayerViewController.player play]; } @end
Swift
... func adsManagerDidRequestContentPause(_ adsManager: IMAAdsManager!) { // Pause the content for the SDK to play ads. playerViewController.player?.pause() hideContentPlayer() } func adsManagerDidRequestContentResume(_ adsManager: IMAAdsManager!) { // Resume the content since the SDK is done playing ads (at least for now). showContentPlayer() playerViewController.player?.play() } }
大功告成!現在,您透過 IMA SDK 請求及顯示廣告。學習 如要進一步瞭解 SDK 的其他功能,請參閱其他指南 GitHub 上的範例。
後續步驟
如要在 iOS 平台上盡量提高廣告收益,請要求應用程式資訊公開和追蹤權限以使用廣告識別碼。