Handle multiple ad requests

  • The IMA SDK for iOS allows publishers to manage multiple concurrent ad requests, especially useful for preloading ads.

  • Publishers can utilize the UserContext field in IMAAdsRequest to associate a custom identifier with each ad request, simplifying differentiation.

  • The provided userContext value can be retrieved later in the adsLoader:adsLoadedWithData or adsLoader:failedWithAdErrorData delegate methods through the IMAAdsLoadedData or IMAAdLoadingErrorData object, respectively.

  • This approach helps ensure the correct ad manager is linked to its corresponding context, streamlining ad management in complex scenarios.

Select platform: HTML5 Android iOS tvOS

Most uses of the IMA SDK only require managing a single ad request at a time. However some edge case implementations, such as preloading ad data before the user selects a video, may require making multiple concurrent requests. Since ad requests are made asynchronously, ensuring the proper ad manager is associated with the correct context can seem to be a daunting task.

To simplify the process of differentiating multiple ad managers, the IMA SDK for iOS allows publishers to pass in any value or object to the UserContext field of any ad request. This value or object can then be retrieved in the AdsLoader:AdsLoadedWithData delegate function, via the IMAAdsLoadedData object's userContext attribute.

Example

...
  adsLoader = IMAAdsLoader(settings: nil)
  adsLoader.delegate = self

  let userContextA = {id: "Request A", element: videoElementA}
  let userContextB = {id: "Request B", element: videoElementB}
  let requestA = IMAAdsRequest(
        adTagUrl: ViewController.AdTagURLString,
        adDisplayContainer: adDisplayContainer,
        contentPlayhead: contentPlayhead,
        userContext: userContextA)
  let requestB = IMAAdsRequest(
        adTagUrl: ViewController.AdTagURLString,
        adDisplayContainer: adDisplayContainer,
        contentPlayhead: contentPlayhead,
        userContext: userContextB)
  adsLoader.requestAds(with: requestA)
  adsLoader.requestAds(with: requestB)

...

// MARK: - IMAAdsLoaderDelegate

func adsLoader(_ loader: IMAAdsLoader!, adsLoadedWith adsLoadedData: IMAAdsLoadedData!) {
  let userContext = adsLoadedData.userContext
  print("Loaded ads for ID: " + userContext.id)
  adsManager = adsLoadedData.adsManager
  adsManager.initialize(with: nil)
}

func adsLoader(_ loader: IMAAdsLoader!, failedWith adErrorData: IMAAdLoadingErrorData!) {
  let userContext = adsLoadingErrorData.userContext
  print("Error loading ads for ID: " + userContext.id)
}

...