Get started with the IMA DAI SDK

IMA SDKs make it easy to integrate multimedia ads into your websites and apps. IMA SDKs can request ads from any VAST-compliant ad server and manage ad playback in your apps. With IMA DAI SDKs, apps make a stream request for ad and content video—either VOD or live content. The SDK then returns a combined video stream, so that you don't have to manage switching between ad and content video within your app.

Select the DAI solution you're interested in

Pod Serving DAI

This guide demonstrates how to integrate the IMA DAI SDK into a simple video player app. If you would like to view or follow along with a completed sample integration, download the PodServingExample from GitHub.

IMA DAI overview

Implementing IMA DAI involves four main SDK components as demonstrated in this guide:

  • IMAAdDisplayContainer – A container object that sits on top of the video playback element and houses the ad UI elements.
  • IMAAdsLoader – An object that requests streams and handles events triggered by stream request response objects. You should only instantiate one ads loader, which can be reused throughout the life of the application.
  • IMAStreamRequest – either an IMAPodVODStreamRequest or an IMAPodStreamRequest.
  • IMAStreamManager – An object that handles dynamic ad insertion streams and interactions with the DAI backend. The stream manager also handles tracking pings and forwards stream and ad events to the publisher.

In addition, to play pod serving streams you must implement a custom VTP handler. This custom VTP handler sends the stream ID to your video technical partner (VTP) along with any other information that it requires to return a stream manifest containing both content and stitched ads. Your VTP will provide instructions on how to implement your custom VTP handler.

Prerequisites

Before you begin, you need the following:

You also need the parameters used to request your stream from the IMA SDK.

Livestream parameters
Network code The network code for your Ad Manager 360 account.
Example: 51636543
Custom Asset Key The custom asset key that identifies your Pod Serving event in Ad Manager 360. This can be created by your manifest manipulator or 3rd party Pod Serving partner.
Example: google-sample
VOD stream parameters
Network code The network code for your Ad Manager 360 account.
Example: 51636543

Create a new Xcode project

In Xcode, create a new iOS project using Objective-C named "PodServingExample".

Add the IMA DAI SDK to the Xcode project

Use one of these three methods to install the IMA DAI SDK.

Install the SDK using CocoaPods (preferred)

CocoaPods is a dependency manager for Xcode projects and is the recommended method for installing the IMA DAI SDK. For more information on installing or using CocoaPods, see the CocoaPods documentation. After you've installed CocoaPods, use the following instructions to install the IMA DAI SDK:

  1. In the same directory as your PodServingExample.xcodeproj file, create a text file called Podfile, and add the following configuration:

    source 'https://github.com/CocoaPods/Specs.git'
    
    platform :ios, '14'
    
    target 'PodServingExample' do
      pod 'GoogleAds-IMA-iOS-SDK'
    end
    

  2. From the directory that contains the Podfile, run:

    pod install --repo-update

Install the SDK using Swift Package Manager

The Interactive Media Ads SDK supports Swift Package Manager starting in version 3.18.4. Follow the following steps to import the Swift package.

  1. In Xcode, install the IMA DAI SDK Swift Package by navigating to File > Add Packages.

  2. In the prompt that appears, search for the IMA DAI SDK Swift Package GitHub repository:

    https://github.com/googleads/swift-package-manager-google-interactive-media-ads-ios
    
  3. Select the version of the IMA DAI SDK Swift Package you want to use. For new projects, we recommend using the Up to Next Major Version.

When you're done, Xcode resolves your package dependencies and downloads them in the background. For more details on how to add package dependencies, see Apple's article.

Manually download and install the SDK

If you don't want to use Swift Package Manager or CocoaPods, you can download the IMA DAI SDK and manually add it to your project.

Create a simple video player

Implement a video player in your main view controller, using an AV player wrapped in a UI view. The IMA SDK uses the UI view to display ad UI elements.

#import "ViewController.h"

#import <AVKit/AVKit.h>

/// Content URL.
static NSString *const kBackupContentUrl =
    @"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8";

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

@property(nonatomic, weak) IBOutlet UIView *videoView;
/// Video player.
@property(nonatomic, strong) AVPlayer *videoPlayer;
@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  self.view.backgroundColor = [UIColor blackColor];

  // Load AVPlayer with the path to your content.
  NSURL *contentURL = [NSURL URLWithString:kBackupContentUrl];
  self.videoPlayer = [AVPlayer playerWithURL:contentURL];

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

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

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

@end

Initialize the ads loader

Import the IMA SDK into your view controller and adopt the IMAAdsLoaderDelegate and IMAStreamManagerDelegate protocols to handle ads loader and stream manager events.

Add these private properties to store key IMA SDK components:

Initialize the ads loader, ad display container, and video display after the view loads.

@import GoogleInteractiveMediaAds;

// ...

@interface ViewController () <IMAAdsLoaderDelegate, IMAStreamManagerDelegate>
/// The entry point for the IMA DAI SDK to make DAI stream requests.
@property(nonatomic, strong) IMAAdsLoader *adsLoader;
/// The container where the SDK renders each ad's user interface elements and companion slots.
@property(nonatomic, strong) IMAAdDisplayContainer *adDisplayContainer;
/// The reference of your video player for the IMA DAI SDK to monitor playback and handle timed
/// metadata.
@property(nonatomic, strong) IMAAVPlayerVideoDisplay *imaVideoDisplay;
/// References the stream manager from the IMA DAI SDK after successful stream loading.
@property(nonatomic, strong) IMAStreamManager *streamManager;

// ...

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  // ...

  self.adsLoader = [[IMAAdsLoader alloc] initWithSettings:nil];
  self.adsLoader.delegate = self;

  // Create an ad display container for rendering each ad's user interface elements and companion
  // slots.
  self.adDisplayContainer =
      [[IMAAdDisplayContainer alloc] initWithAdContainer:self.videoView
                                          viewController:self
                                          companionSlots:nil];

  // Create an IMAAVPlayerVideoDisplay to give the SDK access to your video player.
  self.imaVideoDisplay = [[IMAAVPlayerVideoDisplay alloc] initWithAVPlayer:self.videoPlayer];
}

Make a stream request

When a user presses the play button, make a new stream request. Use the IMAPodStreamRequest class for Live streams. For VOD streams, use the IMAPodVODStreamRequest class.

The stream request requires your stream parameters, as well as a reference to your ad display container and video display.

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

- (void)requestStream {
  // Create a stream request.
  IMAStreamRequest *request;
  if (kStreamType == StreamTypeLive) {
    // Live stream request. Replace the network code and custom asset key with your values.
    request = [[IMAPodStreamRequest alloc] initWithNetworkCode:kNetworkCode
                                                customAssetKey:kCustomAssetKey
                                            adDisplayContainer:adDisplayContainer
                                                  videoDisplay:self.videoDisplay
                                         pictureInPictureProxy:nil
                                                   userContext:nil];
  } else {
    // VOD request. Replace the network code with your value.
    request = [[IMAPodVODStreamRequest alloc] initWithNetworkCode:@kNetworkCode
                                               adDisplayContainer:adDisplayContainer
                                                     videoDisplay:self.videoDisplay
                                            pictureInPictureProxy:nil
                                                      userContext:nil];
  }
  [self.adsLoader requestStreamWithRequest:request];
}

Listen to stream load events

The IMAAdsLoader class calls the IMAAdsLoaderDelegate methods on successful initialization or failure of the stream request.

In the adsLoadedWithData delegate method, set your IMAStreamManagerDelegate. Pass the stream ID to your custom VTP handler, and retrieve the stream manifest URL. For livestreams, load the manifest URL into your video display, and start playback. For VOD streams, pass the manifest URL to the stream manager's loadThirdPartyStream method. This method requests ad event data from Ad Manager 360, then loads the manifest URL and starts playback.

In the failedWithErrorData delegate method, log the error. Optionally, play the backup stream. See DAI best practices.

- (void)adsLoader:(IMAAdsLoader *)loader adsLoadedWithData:(IMAAdsLoadedData *)adsLoadedData {
  NSLog(@"Stream created with: %@.", adsLoadedData.streamManager.streamId);
  self.streamManager = adsLoadedData.streamManager;
  self.streamManager.delegate = self;

  // Build the Pod serving Stream URL.
  NSString *streamID = adsLoadedData.streamManager.streamId;
  // Your custom VTP handler takes the stream ID and returns the stream manifest URL.
  NSString *urlString = gCustomVTPHandler(streamID);
  NSURL *streamUrl = [NSURL URLWithString:urlString];
  if (kStreamType == StreamTypeLive) {
    // Load live streams directly into the AVPlayer.
    [self.videoDisplay loadStream:streamUrl withSubtitles:@[]];
    [self.videoDisplay play];
  } else {
    // Load VOD streams using the `loadThirdPartyStream` method in IMA SDK's stream manager.
    // The stream manager loads the stream, requests metadata, and starts playback.
    [self.streamManager loadThirdPartyStream:streamUrl streamSubtitles:@[]];
  }
}

- (void)adsLoader:(IMAAdsLoader *)loader failedWithErrorData:(IMAAdLoadingErrorData *)adErrorData {
  // Log the error and play the backup content.
  NSLog(@"AdsLoader error, code:%ld, message: %@", adErrorData.adError.code,
        adErrorData.adError.message);
  [self.videoPlayer play];
}

Implement your custom VTP handler

The custom VTP handler sends the viewer's stream ID to your video technical partner (VTP) along with any other information that your VTP requires to return a stream manifest containing both content and stitched ads. Your VTP will provide specific instructions on how to implement your custom VTP handler.

For example, a VTP may include a manifest template URL containing the macro [[STREAMID]]. In this example, the handler inserts the Stream ID in place of the macro and returns the resulting manifest URL.

/// Custom VTP Handler.
///
/// Returns the stream manifest URL from the video technical partner or manifest manipulator.
static NSString *(^gCustomVTPHandler)(NSString *) = ^(NSString *streamID) {
  // Insert synchronous code here to retrieve a stream manifest URL from your video tech partner
  // or manifest manipulation server.
  // This example uses a hardcoded URL template, containing a placeholder for the stream
  // ID and replaces the placeholder with the stream ID.
  NSString *manifestUrl = @"YOUR_MANIFEST_URL_TEMPLATE";
  return [manifestUrl stringByReplacingOccurrencesOfString:@"[[STREAMID]]"
                                                withString:streamID];
};

Listen to ad events

The IMAStreamManager calls the IMAStreamManagerDelegate methods to pass stream events and errors to your application.

For this example, log the primary ad events to the console:

- (void)streamManager:(IMAStreamManager *)streamManager didReceiveAdEvent:(IMAAdEvent *)event {
  NSLog(@"Ad event (%@).", event.typeString);
  switch (event.type) {
    case kIMAAdEvent_STARTED: {
      // Log extended data.
      NSString *extendedAdPodInfo = [[NSString alloc]
          initWithFormat:@"Showing ad %ld/%ld, bumper: %@, title: %@, description: %@, contentType:"
                         @"%@, pod index: %ld, time offset: %lf, max duration: %lf.",
                         (long)event.ad.adPodInfo.adPosition, (long)event.ad.adPodInfo.totalAds,
                         event.ad.adPodInfo.isBumper ? @"YES" : @"NO", event.ad.adTitle,
                         event.ad.adDescription, event.ad.contentType,
                         (long)event.ad.adPodInfo.podIndex, event.ad.adPodInfo.timeOffset,
                         event.ad.adPodInfo.maxDuration];

      NSLog(@"%@", extendedAdPodInfo);
      break;
    }
    case kIMAAdEvent_AD_BREAK_STARTED: {
      NSLog(@"Ad break started");
      break;
    }
    case kIMAAdEvent_AD_BREAK_ENDED: {
      NSLog(@"Ad break ended");
      break;
    }
    case kIMAAdEvent_AD_PERIOD_STARTED: {
      NSLog(@"Ad period started");
      break;
    }
    case kIMAAdEvent_AD_PERIOD_ENDED: {
      NSLog(@"Ad period ended");
      break;
    }
    default:
      break;
  }
}

- (void)streamManager:(IMAStreamManager *)streamManager didReceiveAdError:(IMAAdError *)error {
  NSLog(@"StreamManager error with type: %ld\ncode: %ld\nmessage: %@", error.type, error.code,
        error.message);
  [self.videoPlayer play];
}

Clean up IMA DAI assets

To stop stream playback, stop all ad tracking, and release all of the loaded stream assets, call IMAStreamManager.destroy().

Run your app, and if successful, you can request and play Google DAI streams with the IMA SDK. To learn about more advanced SDK features, see other guides listed in the left-hand sidebar or samples on GitHub.