### Install IMA SDK with CocoaPods for iOS Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side This snippet shows how to add the IMA SDK to an iOS project using CocoaPods. It requires a Podfile in the project directory and specifies the SDK version. The command `pod install --repo-update` is used to install the dependency. ```ruby platform :ios, '15' target "BasicExample" do pod 'GoogleAds-IMA-iOS-SDK', '~> 3.28.10' end Podfile ``` -------------------------------- ### Start Ad Playback on LOADED Event (Objective-C, Swift) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side This snippet demonstrates how to start ad playback when the IMA SDK signals that ads have been loaded. It listens for the kIMAAdEvent_LOADED event and calls the start method on the ads manager. This is crucial for initiating the ad experience after ads are prepared. ```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]; } } ViewController.m ``` ```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() } } PlayerContainerViewController.swift ``` -------------------------------- ### Manually add GoogleInteractiveMediaAds.framework Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/index This outlines the manual installation process for the IMA SDK. It involves downloading the SDK, adding the GoogleInteractiveMediaAds.framework to your Xcode project's 'Link Binary With Libraries' phase, and including the '-ObjC' linker flag in your build settings. ```bash -ObjC ``` -------------------------------- ### IMAAdsManagerAdDidStartBuffering Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMAAdsManagerDelegate_hl=id This method is called when the ads manager starts buffering the current ad. ```APIDOC ## adsManagerAdDidStartBuffering ### Description This delegate method is called when the ads manager starts buffering the current ad. ### Method `optional func adsManagerAdDidStartBuffering(_ adsManager: IMAAdsManager)` (Swift) `- (void)adsManagerAdDidStartBuffering:(nonnull IMAAdsManager *)adsManager;` (Objective-C) ### Endpoint N/A (Delegate Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) This is a callback method, not an endpoint with a direct response. #### Response Example None ``` -------------------------------- ### adsManagerAdDidStartBuffering Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMAAdsManagerDelegate_hl=pl This method is called when the IMAAdsManager starts buffering an ad. ```APIDOC ## adsManagerAdDidStartBuffering ### Description Called when the IMAAdsManager starts buffering an ad. ### Method `optional func adsManagerAdDidStartBuffering(_ adsManager: IMAAdsManager)` (Swift) `- (void)adsManagerAdDidStartBuffering:(nonnull IMAAdsManager *)adsManager;` (Objective-C) ### Endpoint N/A (Delegate Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### adsManagerAdDidStartBuffering Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMAAdsManagerDelegate_hl=ko This method is called when the IMAAdsManager detects that an ad has started buffering. ```APIDOC ## adsManagerAdDidStartBuffering ### Description Called when the IMAAdsManager starts buffering an ad. ### Method `optional func adsManagerAdDidStartBuffering(_ adsManager: IMAAdsManager)` (Swift) `- (void)adsManagerAdDidStartBuffering:(nonnull IMAAdsManager *)adsManager;` (Objective-C) ### Endpoint N/A (Delegate Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) None #### Response Example None ``` -------------------------------- ### adsManagerAdDidStartBuffering Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMAAdsManagerDelegate_hl=tr This method is called when the ads manager starts buffering the current ad. ```APIDOC ## adsManagerAdDidStartBuffering ### Description Called when the ads manager starts buffering the current ad. ### Method `optional func adsManagerAdDidStartBuffering(_ adsManager: IMAAdsManager)` (Swift) `- (void)adsManagerAdDidStartBuffering:(nonnull IMAAdsManager *)adsManager;` (Objective-C) ### Parameters - **adsManager** (IMAAdsManager) - The IMAAdsManager tracking the stalled ad. ``` -------------------------------- ### Import IMA SDK and Declare Ad Variables (Swift) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/index This snippet shows how to import the IMA SDK in a Swift project and declare variables for ad management. It initializes `IMAAdsLoader`, `IMAAdsManager`, and sets up `IMAAVPlayerContentPlayhead` with an `AVPlayer`. An example ad tag URL is also included. ```Swift import GoogleInteractiveMediaAds PlayerContainerViewController.swift 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) }() PlayerContainerViewController.swift ``` -------------------------------- ### adsManagerAdDidStartBuffering Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMAAdsManagerDelegate This method is called when the ads manager detects that an ad has started buffering. ```APIDOC ## adsManagerAdDidStartBuffering ### Description Called when the ads manager detects that an ad has started buffering. ### Method `optional func adsManagerAdDidStartBuffering(_ adsManager: IMAAdsManager) - (void)adsManagerAdDidStartBuffering:(nonnull IMAAdsManager *)adsManager;` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Get Adapter and Ad SDK Versions Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMASecureSignalsAdapter_hl=es Retrieves the version of the secure signals adapter and the version of the associated ad SDK. These methods are essential for version tracking and compatibility checks. ```Swift let adapterVersion = MySecureSignalsAdapter.adapterVersion() let adSDKVersion = MySecureSignalsAdapter.adSDKVersion() print("Adapter Version: \(adapterVersion)") print("Ad SDK Version: \(adSDKVersion)") ``` -------------------------------- ### Install IMA SDK using CocoaPods (Objective-C) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/index This code snippet shows how to add the IMA SDK to your Xcode project using CocoaPods. Ensure you have CocoaPods installed and a Podfile in your project directory. The SDK version is specified as '~> 3.28.10'. ```ruby platform :ios, '15' target "BasicExample" do pod 'GoogleAds-IMA-iOS-SDK', '~> 3.28.10' end ``` -------------------------------- ### adsManagerAdDidStartBuffering Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMAAdsManagerDelegate_hl=th This method is called when the ads manager starts buffering the current ad. It allows you to track when an ad begins the buffering process. ```APIDOC ## adsManagerAdDidStartBuffering ### Description Called when the ads manager starts buffering the current ad. ### Method `optional func adsManagerAdDidStartBuffering(_ adsManager: IMAAdsManager)` (Swift) `- (void)adsManagerAdDidStartBuffering:(nonnull IMAAdsManager *)adsManager;` (Objective-C) ### Endpoint N/A (Delegate Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) This is a callback method, no direct response is returned. #### Response Example None ``` -------------------------------- ### Declare IMA SDK Variables (Swift) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side Declares essential IMA SDK variables in Swift: `adsLoader` for initiating ad requests, `adsManager` for handling ad playback, and a lazy-initialized `contentPlayhead` to track video progress. An example ad tag URL is also included. ```Swift 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) }() PlayerContainerViewController.swift ``` -------------------------------- ### adsManagerAdDidStartBuffering Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMAAdsManagerDelegate_hl=vi This method is called when the ads manager detects that an ad has started buffering. ```APIDOC ## adsManagerAdDidStartBuffering ### Description Called when the ads manager starts buffering the current ad. ### Method `optional func adsManagerAdDidStartBuffering(_ adsManager: IMAAdsManager)` (Swift) `- (void)adsManagerAdDidStartBuffering:(nonnull IMAAdsManager *)adsManager;` (Objective-C) ### Endpoint N/A (Delegate Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) This is a delegate method callback, not an API response. #### Response Example None ``` -------------------------------- ### adsManagerAdDidStartBuffering Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMAAdsManagerDelegate_hl=ja This method is called when the ads manager detects that an ad has started buffering. ```APIDOC ## adsManagerAdDidStartBuffering ### Description Called when the ads manager detects that an ad has started buffering. ### Method `optional func adsManagerAdDidStartBuffering(_ adsManager: IMAAdsManager)` (Swift) `- (void)adsManagerAdDidStartBuffering:(nonnull IMAAdsManager *)adsManager;` (Objective-C) ### Parameters - **adsManager** (IMAAdsManager) - The IMAAdsManager tracking the stalled ad. ``` -------------------------------- ### IMAVideoDisplay Play Method Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMAVideoDisplay Called to inform the VideoDisplay to start playback of the current ad or stream. ```swift func play() ``` ```objectivec - (void)play; ``` -------------------------------- ### Get Ad SDK Version Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMASecureSignalsAdapter_hl=ja Retrieves the version of the associated Ad SDK. This is useful for ensuring compatibility between the adapter and the main IMA SDK. ```Swift static func adSDKVersion() -> IMAVersion ``` ```Objective-C + (nonnull IMAVersion *)adSDKVersion; ``` -------------------------------- ### Get Adapter and Ad SDK Versions Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMASecureSignalsAdapter Retrieves the version of the Secure Signal adapter and the version of the ad SDK. These methods return an IMAVersion object. ```Swift static func adapterVersion() -> IMAVersion ``` ```Objective-C + (nonnull IMAVersion *)adapterVersion; ``` ```Swift static func adSDKVersion() -> IMAVersion ``` ```Objective-C + (nonnull IMAVersion *)adSDKVersion; ``` -------------------------------- ### Add IMA SDK to Podfile (CocoaPods) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/secure-signals-developer This snippet shows how to add the Google IMA SDK for iOS to your project's Podfile using CocoaPods. It specifies the source repository for pods and sets the minimum iOS platform version. This is a prerequisite for installing the SDK. ```ruby source 'https://github.com/CocoaPods/Specs.git' platform :ios, '10' target "BasicExample" do pod 'GoogleAds-IMA-iOS-SDK', '~> 3.17.0' end ``` -------------------------------- ### IMAAdsManager Ad Buffering Events Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMAAdsManagerDelegate_hl=pt-br Delegate methods to inform when an ad starts buffering or when buffering progresses to a specific media time. ```APIDOC ## IMAAdsManager Ad Buffering Delegate Methods ### adsManagerAdDidStartBuffering This method is called when the ads manager detects that an ad has started buffering. ### Method `optional func adsManagerAdDidStartBuffering(_ adsManager: IMAAdsManager) - (void)adsManagerAdDidStartBuffering:(nonnull IMAAdsManager *)adsManager;` ### Parameters #### Path Parameters * `adsManager` (IMAAdsManager) - Required - The IMAAdsManager tracking the stalled ad. ### Response #### Success Response (200) This method does not return a value. --- ### adsManager:adDidBufferToMediaTime: This method is called as the current ad media buffers, providing the current buffered media time. ### Method `optional func adsManager(_ adsManager: IMAAdsManager, adDidBufferToMediaTime mediaTime: TimeInterval) - (void)adsManager:(nonnull IMAAdsManager *)adsManager adDidBufferToMediaTime:(NSTimeInterval)mediaTime;` ### Parameters #### Path Parameters * `adsManager` (IMAAdsManager) - Required - The IMAAdsManager tracking the ad’s media buffer. * `mediaTime` (TimeInterval) - Required - The current buffered media time in seconds. ### Response #### Success Response (200) This method does not return a value. ``` -------------------------------- ### Notify Start of Buffering (Swift, Objective-C) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMAVideoDisplayDelegate Informs the SDK that the ad's media buffer is empty and playback is likely to stall. This is an optional delegate method called on the IMAVideoDisplay object. ```Swift optional func videoDisplayDidStartBuffering(_ videoDisplay: any IMAVideoDisplay) ``` ```Objective-C - (void)videoDisplayDidStartBuffering:(nonnull id)videoDisplay; ``` -------------------------------- ### Get Adapter Version Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMASecureSignalsAdapter_hl=ja Retrieves the version of the Secure Signals adapter. This method is used to identify the specific version of the adapter implementation being used. ```Swift static func adapterVersion() -> IMAVersion ``` ```Objective-C + (nonnull IMAVersion *)adapterVersion; ``` -------------------------------- ### Set Up Video Player Variables (Swift) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side Defines the content URL and initializes an AVPlayer instance. It also sets up a lazy-initialized AVPlayerLayer for rendering the video and a lazy-initialized UIView to contain the player. ```swift 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) }() PlayerContainerViewController.swift ``` -------------------------------- ### Initialize Secure Signal Adapter Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMASecureSignalsAdapter_hl=es Demonstrates the initialization of the Secure Signal adapter. This is a fundamental step before using the adapter's other functionalities. The initializer returns an optional instance. ```Swift let adapter: IMASecureSignalsAdapter? = MySecureSignalsAdapter.init() if adapter == nil { print("Failed to initialize adapter.") } ``` -------------------------------- ### Initialize Video Player and View (Swift) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side Configures the video view with constraints and adds the player layer to it. It also sets up observer for the content's completion notification and ensures the player layer frame is updated on view appearance and transitions. ```swift 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() } PlayerContainerViewController.swift ``` -------------------------------- ### Set Up Video Player Variables (Objective-C) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side Declares instance variables for the video player (AVPlayer), play button, and the view that will host the video content. It also conforms to IMAAdsLoaderDelegate and IMAAdsManagerDelegate protocols for ad management. ```objectivec @interface ViewController () /// 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;ViewController.m ``` -------------------------------- ### IMASecureSignalsAdapter Protocol Reference Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMASecureSignalsAdapter_hl=pt-br Reference for the IMASecureSignalsAdapter protocol, including its initialization, version retrieval, and signal collection methods. ```APIDOC ## IMASecureSignalsAdapter `@protocol IMASecureSignalsAdapter ` Adapter that provides secure signal (3rd party signal only) to the IMA SDK to be included in an auction. ### -init Initializes the Secure Signal adapter. #### Declaration Swift ``` init?() ``` Objective-C ``` - (nullable instancetype)init; ``` ### +adapterVersion The version of the adapter. #### Declaration Swift ``` static func adapterVersion() -> IMAVersion ``` Objective-C ``` + (nonnull IMAVersion *)adapterVersion; ``` ### +adSDKVersion The version of the ad SDK. #### Declaration Swift ``` static func adSDKVersion() -> IMAVersion ``` Objective-C ``` + (nonnull IMAVersion *)adSDKVersion; ``` ### -collectSignalsWithCompletion: Asks the receiver for encrypted signals. Signals are provided to the 3PAS at request time. The receiver must call `completionHandler` with signals or an error. This method is called on a non-main thread. The receiver should avoid using the main thread to prevent signal collection timeouts. #### Declaration Swift ``` func collectSignals() async throws -> String ``` Objective-C ``` - (void)collectSignalsWithCompletion: (nonnull IMASignalCompletionHandler)completion; ``` #### Parameters ` _completion_ ` | The block to call when signal collection is complete. ---|--- ``` -------------------------------- ### Swift: Set Up Video Player Properties and View Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/index Defines properties for the AVPlayer, AVPlayerLayer, and a container UIView for video rendering. It also sets up layout constraints for the video view. Requires AVFoundation and UIKit. ```swift 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) }() PlayerContainerViewController.swift ``` ```swift 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 }() ``` -------------------------------- ### Initialize Video Player and Load Ads (Objective-C) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side Initializes the AVPlayer with a content URL and sets up the player layer within the designated video view. It also includes logic for requesting ads and handling the content's completion notification. This code is executed when the view loads. ```objectivec @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; } ViewController.m ``` -------------------------------- ### Objective-C: Set Up Video Player Properties Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/index Declares properties for the content video player, play button, and video rendering view. Conforms to IMA SDK delegate protocols. Depends on UIKit and AVFoundation. ```objectivec @interface ViewController () /// 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; ViewController.m ``` -------------------------------- ### Initialize Content Playhead and Observer (Objective-C) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side Initializes the `IMAAVPlayerContentPlayhead` with the AVPlayer and sets up an observer for the `AVPlayerItemDidPlayToEndTimeNotification`. This ensures the SDK can track content progress and detect when content finishes playing. ```Objective-C // 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]; ViewController.m ``` -------------------------------- ### Import AVFoundation for Video Player (Swift) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side Imports the AVFoundation framework, necessary for audio and video operations in Swift. This enables the creation and management of an AVPlayer instance. ```swift import AVFoundation PlayerContainerViewController.swift ``` -------------------------------- ### IMASecureSignalsAdapter Protocol Reference Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMASecureSignalsAdapter This section provides a detailed reference for the IMASecureSignalsAdapter protocol, outlining its methods for initializing the adapter, retrieving version information, and collecting secure signals. ```APIDOC ## IMASecureSignalsAdapter Protocol ### Description The `IMASecureSignalsAdapter` protocol defines an adapter that provides secure third-party signals to the IMA SDK for inclusion in an ad auction. ### Methods #### -init ##### Description Initializes the Secure Signal adapter. ##### Declaration **Swift:** ```swift init?() ``` **Objective-C:** ```objc - (nullable instancetype)init; ``` #### +adapterVersion ##### Description Returns the version of the adapter. ##### Declaration **Swift:** ```swift static func adapterVersion() -> IMAVersion ``` **Objective-C:** ```objc + (nonnull IMAVersion *)adapterVersion; ``` #### +adSDKVersion ##### Description Returns the version of the ad SDK. ##### Declaration **Swift:** ```swift static func adSDKVersion() -> IMAVersion ``` **Objective-C:** ```objc + (nonnull IMAVersion *)adSDKVersion; ``` #### -collectSignalsWithCompletion: ##### Description Asks the receiver for encrypted signals. Signals are provided to the 3PAS at request time. The receiver must call `completionHandler` with signals or an error. This method is called on a non-main thread. The receiver should avoid using the main thread to prevent signal collection timeouts. ##### Declaration **Swift:** ```swift func collectSignals() async throws -> String ``` **Objective-C:** ```objc - (void)collectSignalsWithCompletion: (nonnull IMASignalCompletionHandler)completion; ``` ##### Parameters - `completion` (IMASignalCompletionHandler) - The block to call when signal collection is complete. ``` -------------------------------- ### Import AVFoundation for Video Player (Objective-C) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side Imports the AVFoundation framework, which is essential for handling audio and video playback in Objective-C. This is a prerequisite for creating an AVPlayer instance. ```objectivec #import "ViewController.h" @import AVFoundation; ViewController.m ``` -------------------------------- ### Initialize Secure Signals Adapter (Swift) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/secure-signals-developer Shows the Swift implementation for initializing the secure signals adapter. This method is invoked once by the IMA SDK to set up necessary components before signal collection begins. ```Swift ... @objc(MySecureSignalsAdapter) public class MySecureSignalsAdapter: IMASecureSignalsAdapter { ... private var initError override init() { super.init() do { // Initialize your SDK and any dependencies. ... } catch { // Build NSError to be passed by Signal Collector. self.initError = ...; } } } ... ``` -------------------------------- ### IMAStreamManagerDelegate Protocol Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols_hl=ko A callback protocol for the IMAStreamManager. ```APIDOC ## IMAStreamManagerDelegate Protocol ### Description A callback protocol for IMAStreamManager. ### Method N/A (Protocol Definition) ### Endpoint N/A (Protocol Definition) ### Parameters N/A (Protocol Definition) ### Request Example N/A (Protocol Definition) ### Response N/A (Protocol Definition) ``` -------------------------------- ### Objective-C: Initialize and Configure Video Player Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/index Initializes the AVPlayer with a content URL, creates an AVPlayerLayer, adds it to the video view, and sets up a notification for content completion. Also initiates the IMA AdsLoader. Requires a valid content URL and an ad tag URL. ```objectivec @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; } ViewController.m ``` -------------------------------- ### Objective-C: Import AVFoundation and IMA SDK Dependencies Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/index Imports necessary frameworks for media playback and IMA SDK integration. Requires AVFoundation for video and IMA SDK for ads. No specific input/output, just framework availability. ```objectivec #import "ViewController.h" @import AVFoundation; ViewController.m ``` -------------------------------- ### Protocols Reference Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols_hl=ru This section details the various protocols available in the IMA SDK for iOS, which are essential for managing ad playback, loading, and display functionalities. ```APIDOC ## IMAAVPlayerVideoDisplayDelegate ### Description A callback protocol for IMAAVPlayerVideoDisplayDelegate. ### Declaration #### Swift ```swift protocol IMAAVPlayerVideoDisplayDelegate : NSObjectProtocol ``` #### Objective-C ```objc @protocol IMAAVPlayerVideoDisplayDelegate @end ``` ## IMAAdPlaybackInfo ### Description Groups various properties of the ad player. ### Declaration #### Swift ```swift protocol IMAAdPlaybackInfo : NSObjectProtocol ``` #### Objective-C ```objc @protocol IMAAdPlaybackInfo @end ## IMAAdsLoaderDelegate ### Description Delegate object that receives state change callbacks from IMAAdsLoader. ### Declaration #### Swift ```swift protocol IMAAdsLoaderDelegate ``` #### Objective-C ```objc @protocol IMAAdsLoaderDelegate @end ## IMAAdsManagerDelegate ### Description A callback protocol for IMAAdsManager. ### Declaration #### Swift ```swift protocol IMAAdsManagerDelegate ``` #### Objective-C ```objc @protocol IMAAdsManagerDelegate @end ## IMALinkOpenerDelegate ### Description Signals that a link has been opened/closed. For an external app (Mobile Safari/App deep link), the delegate is only notified before opening. ### Declaration #### Swift ```swift protocol IMALinkOpenerDelegate : NSObjectProtocol ``` #### Objective-C ```objc @protocol IMALinkOpenerDelegate @end ## IMACompanionDelegate ### Description Delegate to receive events from the companion ad slot. ### Declaration #### Swift ```swift protocol IMACompanionDelegate : NSObjectProtocol ``` #### Objective-C ```objc @protocol IMACompanionDelegate @end ## IMAContentPlayhead ### Description Defines an interface for a class that tracks video content progress and exposes a key value observable property |currentTime|. The SDK provides an implementation for tracking AVPlayer-based playback in the IMAAVPlayerContentPlayhead. Publishers can supply their own implementation by implementing this interface and this way support any other video playback implementation they might have. ### Declaration #### Swift ```swift protocol IMAContentPlayhead ``` #### Objective-C ```objc @protocol IMAContentPlayhead @end ## IMASecureSignalsAdapter ### Description Adapter that provides secure signal(3rd party signal only) to the IMA SDK to be included in an auction. ### Declaration #### Swift ```swift protocol IMASecureSignalsAdapter : NSObjectProtocol ``` #### Objective-C ```objc @protocol IMASecureSignalsAdapter @end ## IMAStreamManagerDelegate ### Description A callback protocol for IMAStreamManager. ### Declaration #### Swift ```swift protocol IMAStreamManagerDelegate ``` #### Objective-C ```objc @protocol IMAStreamManagerDelegate @end ## IMAVideoDisplayDelegate ### Description Delegate object that receives state change callbacks from IMAVideoDisplay. ### Declaration (No explicit declaration provided in the input text for this protocol) ``` -------------------------------- ### Swift: Import AVFoundation Dependency Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/index Imports the AVFoundation framework, which is essential for handling audio and video playback on iOS. This is a prerequisite for creating the video player. ```swift import AVFoundation PlayerContainerViewController.swift ``` -------------------------------- ### OM SDK Sample Pre-roll Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/tags This endpoint provides an ad tag for a pre-roll ad incorporating the OM SDK (Optical Measurement SDK). This is used for testing ad verification and measurement integrations. ```APIDOC ## GET /gampad/ads ### Description Serves ad tags that include OM SDK (Optical Measurement SDK) parameters for pre-roll ads. Useful for testing ad verification and measurement solutions. ### Method GET ### Endpoint https://pubads.g.doubleclick.net/gampad/ads ### Query Parameters - **iu** (string) - Required - Ad unit path. - **env** (string) - Required - Environment type (e.g., vp). - **gdfp_req** (integer) - Required - Google Ad Manager request flag. - **output** (string) - Required - Output format (e.g., vast). - **sz** (string) - Required - Ad size. - **description_url** (string) - Optional - URL for describing the content. - **vpmute** (integer) - Optional - Video player mute status (0=unmuted, 1=muted). - **vpa** (integer) - Optional - Video player autoplay status (0=no, 1=yes). - **vad_format** (string) - Optional - Ad format (e.g., linear). - **url** (string) - Optional - URL of the page requesting the ad. - **vpos** (string) - Optional - Video position (e.g., preroll). - **unviewed_position_start** (integer) - Optional - Specifies start position for unviewed ad tracking. - **correlator** (string) - Optional - Cache busting parameter. ### Request Example ```json { "example": "https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/omid_ad_samples&env=vp&gdfp_req=1&output=vast&sz=640x480&description_url=http%3A%2F%2Ftest_site.com%2Fhomepage&vpmute=0&vpa=0&vad_format=linear&url=http%3A%2F%2Ftest_site.com&vpos=preroll&unviewed_position_start=1&correlator=" } ``` ### Response #### Success Response (200) - **VAST XML** (string) - The VAST XML document containing ad information. ``` -------------------------------- ### Initialize Secure Signals Adapter (Objective-C) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/secure-signals-developer Demonstrates the initialization process for the secure signals adapter in Objective-C. This method is called once by the IMA SDK and is used for setting up encryption, caches, or pre-calculating signals. ```Objective-C ... @interface MySecureSignalsAdapter @property(nonatomic) NSError *initError; @end ... /** * Initialize your SDK and any dependencies. * IMA SDK calls this function exactly once before signal collection. */ - (instancetype)init { self = [super init]; @try { // Initialize your SDK and any dependencies. ... } @catch(NSException *exception) { // Build NSError to be passed by Signal Collector. _initError = ...; } return self; } ... ``` -------------------------------- ### Swift: Initialize Video Player and Handle View Transitions Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/index Initializes the player layer, sets the IMA ads loader delegate, and adds an observer for the AVPlayerItemDidPlayToEndTime notification. It also ensures the player layer's frame is updated during view appearance and transitions. ```swift // 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() } PlayerContainerViewController.swift ``` -------------------------------- ### Import IMA SDK for iOS (Objective-C) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side Imports the Google Interactive Media Ads (IMA) SDK into an Objective-C project. This is the first step to using IMA SDK functionalities. ```Objective-C @import GoogleInteractiveMediaAds; ViewController.m ``` -------------------------------- ### Initialize IMASecureSignalsAdapter Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMASecureSignalsAdapter Initializes the Secure Signal adapter. This method is available in both Swift and Objective-C. ```Swift init?() ``` ```Objective-C - (nullable instancetype)init; ``` -------------------------------- ### IMASecureSignalsAdapter Protocol Reference Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMASecureSignalsAdapter_hl=ja Documentation for the IMASecureSignalsAdapter protocol, defining methods for secure signal integration with the IMA SDK. ```APIDOC ## IMASecureSignalsAdapter ```swift @protocol IMASecureSignalsAdapter ``` Adapter that provides secure signal (3rd party signal only) to the IMA SDK to be included in an auction. ### -init Initializes the Secure Signal adapter. #### Declaration Swift ```swift init?() ``` Objective-C ```objectivec - (nullable instancetype)init; ``` ### +adapterVersion The version of the adapter. #### Declaration Swift ```swift static func adapterVersion() -> IMAVersion ``` Objective-C ```objectivec + (nonnull IMAVersion *)adapterVersion; ``` ### +adSDKVersion The version of the ad SDK. #### Declaration Swift ```swift static func adSDKVersion() -> IMAVersion ``` Objective-C ```objectivec + (nonnull IMAVersion *)adSDKVersion; ``` ### -collectSignalsWithCompletion: Asks the receiver for encrypted signals. Signals are provided to the 3PAS at request time. The receiver must call `completionHandler` with signals or an error. This method is called on a non-main thread. The receiver should avoid using the main thread to prevent signal collection timeouts. #### Declaration Swift ```swift func collectSignals() async throws -> String ``` Objective-C ```objectivec - (void)collectSignalsWithCompletion: (nonnull IMASignalCompletionHandler)completion; ``` #### Parameters - `completion` (IMASignalCompletionHandler) - The block to call when signal collection is complete. ``` -------------------------------- ### IMAContentPlayhead Protocol Reference Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMAContentPlayhead_hl=ru Documentation for the IMAContentPlayhead protocol, which defines an interface for tracking video content progress and exposing the current playback time as a key-value observable property. ```APIDOC ## IMAContentPlayhead Protocol ### Description Defines an interface for a class that tracks video content progress and exposes a key-value observable property `currentTime`. The SDK provides an implementation for tracking AVPlayer-based playback in the `IMAAVPlayerContentPlayhead`. Publishers can supply their own implementation by implementing this interface to support other video playback implementations. ### Method N/A (Protocol Definition) ### Endpoint N/A (Protocol Definition) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example N/A ## currentTime Property ### Description Reflects the current playback time in seconds for the content. The property is key-value observable. ### Method N/A (Property Getter) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example N/A ### Declaration #### Swift ```swift var currentTime: TimeInterval { get } ``` #### Objective-C ```objectivec @property (nonatomic, readonly) NSTimeInterval currentTime; ``` ``` -------------------------------- ### Register Video Controls Overlays (Objective-C) Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/omsdk This Objective-C code demonstrates how to create and register views that function as video controls overlays (e.g., transparent tap areas, pause buttons) as friendly obstructions with the IMA SDK's ad display container. Ensure these obstructions are registered before ad playback begins. The `detailedReason` must adhere to IAB standards. ```Objective-C UIView *myTransparentTapOverlay = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 250)]; UIButton *myPauseButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 10)]; // Substitute "myTransparentTapOverlay" and "myPauseButton" with the elements // you want to register as video controls overlays. // Make sure to register before ad playback starts. IMAFriendlyObstruction *overlayObstruction = [[IMAFriendlyObstruction alloc] initWithView:myTransparentTapOverlay purpose:IMAFriendlyObstructionPurposeNotVisible detailedReason:@"This overlay is transparent"]; IMAFriendlyObstruction *pauseButtonObstruction = [[IMAFriendlyObstruction alloc] initWithView:myPauseButton purpose:IMAFriendlyObstructionPurposeMediaControls detailedReason:@"This is the video player pause button"]; [displayContainer registerFriendlyObstruction:overlayObstruction]; [displayContainer registerFriendlyObstruction:pauseButtonObstruction]; ``` -------------------------------- ### Retrieve Adapter and Ad SDK Versions Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Protocols/IMASecureSignalsAdapter_hl=ko Retrieves the versions of the Secure Signals adapter and the main IMA ad SDK. These methods are crucial for tracking compatibility and debugging. Both Swift and Objective-C provide static methods for this purpose. ```swift static func adapterVersion() -> IMAVersion static func adSDKVersion() -> IMAVersion ``` ```objc + (nonnull IMAVersion *)adapterVersion; + (nonnull IMAVersion *)adSDKVersion; ``` -------------------------------- ### Implement Secure Signals Adapter in Swift Source: https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/secure-signals-developer Swift implementation of the IMASecureSignalsAdapter. This includes initializing the adapter, collecting and encrypting signals, and providing adapter and SDK versions. It handles initialization and collection errors using Swift's do-catch blocks and passing NSData objects to the IMA SDK. ```swift @objc(MySecureSignalsAdapter) public class MySecureSignalsAdapter: IMASecureSignalsAdapter { static let VersionMajor = 1; static let VersionMinor = 0; static let VersionPatch = 1; private var initError override init() { super.init() do { // Initialize your SDK and any dependencies. ... } catch { // Build NSError to be passed by Signal Collector. self.initError = ...; } } public func collectSignals(completion: @escaping IMASignalCompletionHandler) { if (self.initError) { completion(nil, self.initError) return } do { // Collect and encrypt the signals. var signals = ... // Pass the encrypted signals to IMA SDK. completion(signals, nil) } catch { NSError collectSignalError = ... // Pass signal collection failures to IMA SDK. completion(nil, collectSignalError) } } public static func adapterVersion() -> IMAVersion { let adapterVersion = IMAVersion() adapterVersion.majorVersion = self.VersionMajor adapterVersion.minorVersion = self.VersionMinor adapterVersion.patchVersion = self.VersionPatch return adapterVersion } public static func adSDKVersion() -> IMAVersion { // Request the version from your SDK and convert to an IMAVersion. let mySDKVersion = ... let adSDKVersion = IMAVersion() adSDKVersion.majorVersion = mySDKVersion[0] adSDKVersion.minorVersion = mySDKVersion[1] adSDKVersion.patchVersion = mySDKVersion[2] return adSDKVersion } } ```