Xử lý nhiều yêu cầu quảng cáo bằng UserContext

Hầu hết các trường hợp sử dụng SDK IMA chỉ yêu cầu quản lý một yêu cầu quảng cáo tại một thời điểm. Tuy nhiên, một số phương pháp triển khai yêu cầu đặc biệt (chẳng hạn như tải trước dữ liệu quảng cáo trước khi người dùng chọn video) có thể đòi hỏi việc thực hiện nhiều yêu cầu đồng thời. Vì yêu cầu quảng cáo được thực hiện không đồng bộ, việc đảm bảo liên kết đúng trình quản lý quảng cáo với ngữ cảnh chính xác có thể là một tác vụ khó khăn.

Để đơn giản hoá quá trình phân biệt nhiều trình quản lý quảng cáo, SDK IMA cho tvOS cho phép nhà xuất bản chuyển bất kỳ giá trị hoặc đối tượng nào vào trường UserContext của bất kỳ yêu cầu quảng cáo nào. Sau đó, bạn có thể truy xuất giá trị hoặc đối tượng này trong hàm uỷ quyền AdsLoader:AdsLoadedWithData, thông qua thuộc tính userContext của đối tượng IMAAdsLoadedData.

Ví dụ:

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

...