Handling multiple ad requests with UserContext

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)
}

...