iOS에서 IMA DAI SDK 사용

Google Cloud Video Stitcher API에 등록된 VOD 스트림 재생

이 가이드에서는 iOS용 IMA DAI SDK를 사용하여 Google Cloud VOD 스트림 세션을 요청하고 재생하는 방법을 설명합니다.

이 가이드에서는 IMA DAI용 시작 가이드의 기본 예시를 설명합니다.

다른 플랫폼과 통합하거나 IMA 클라이언트 측 SDK를 사용하는 방법에 대한 자세한 내용은 양방향 미디어 광고 SDK를 참조하세요.

Google Cloud 프로젝트 설정

IMA SDK에서 사용할 다음 변수를 입력합니다.

위치
VOD 구성이 생성된 Google Cloud 리전: LOCATION
프로젝트 번호
Video Stitcher API를 사용하는 Google Cloud 프로젝트 번호: PROJECT_NUMBER
OAuth 토큰

Video Stitcher 사용자 역할이 포함된 서비스 계정의 단기 OAuth 토큰:

OAUTH_TOKEN

단기 OAuth 토큰 만들기에 대해 자세히 알아보세요. OAuth 토큰은 만료되지 않은 한 여러 요청에서 재사용될 수 있습니다.

네트워크 코드

광고 요청에 사용되는 Ad Manager 네트워크 코드: NETWORK_CODE

VOD 구성 ID

VOD 스트림의 VOD 구성 ID입니다. VOD_CONFIG_ID

클라우드 병합으로 VOD 구성 만들기 가이드에서 VOD 구성 ID 만들기에 대해 자세히 알아보세요.

사용자 컨텍스트
요청 추적에 사용되는 사용자 컨텍스트. nil일 수 있습니다. 이 가이드에서 기본값은 nil입니다.

기본 예시 설정

IMA iOS DAI GitHub 출시 페이지로 이동하여 기본 Objective-C 예시를 다운로드합니다. 이 예시는 CocoaPods를 사용하여 IMA DAI SDK를 로드하는 iOS Xcode 프로젝트입니다. Swift를 사용하는 경우 IMA에는 iOS 샘플 앱이 없지만 이 가이드의 뒷부분에 있는 Swift 코드 스니펫에서 자체 앱에 IMAVideoStitcherVODStreamRequest를 구현하는 방법을 확인하세요.

샘플 실행을 준비하려면 CocoaPods가 설치되어 있는지 확인한 후 터미널에서 기본 예시 폴더를 열고 다음 명령어를 실행합니다.

pod install --repo-update

이 명령어가 완료되면 프로젝트 폴더에 BasicExample.xcworkspace라는 파일이 표시됩니다. Xcode에서 이 파일을 열고 샘플을 실행하여 테스트 동영상과 광고가 예상대로 재생되는지 확인합니다.

VOD 스트림 요청

샘플 스트림을 광고가 병합된 VOD 스트림으로 바꾸려면 IMAVideoStitcherVODStreamRequest를 사용하여 Google Ad Manager로 광고 세션을 만듭니다. Google Ad Manager UI를 사용하면 모니터링 및 디버깅용으로 생성된 DAI 세션을 찾을 수 있습니다.

기존 샘플에는 Google DAI 서버에서 VOD 스트림이나 라이브 스트림을 요청하는 예시가 있습니다. Google Cloud Video Stitcher API에서 사용하려면 현재 requestStream 함수를 IMAVideoStitcherVODStreamRequest 클래스를 사용하는 함수로 바꿔야 합니다.

예를 들면 다음과 같습니다.

Objective-C

ViewController.m

...

#import <GoogleInteractiveMediaAds/GoogleInteractiveMediaAds.h>
/// The Stream's VOD config ID.
static NSString *const kVODConfigID = @"VOD_CONFIG_ID";
/// The Network Code used by the Video Stitcher API.
static NSString *const kNetworkCode = @"NETWORK_CODE";
/// The Google Cloud project using the Video Stitcher API.
static NSString *const kProjectNumber = @"PROJECT_NUMBER";
/// The Google Cloud region containing your project.
static NSString *const kLocation = @"LOCATION";
/// An OAuth Token created by a Google Cloud account with Video Stitcher API
/// permissions.
static NSString *const kOAuthToken = @"OAUTH_TOKEN";

/// Fallback URL in case something goes wrong in loading the stream. If all goes well, this will not
/// be used.
static NSString *const kBackupStreamURLString =
    @"http://googleimadev-vh.akamaihd.net/i/big_buck_bunny/bbb-,480p,720p,1080p,.mov.csmil/"
    @"master.m3u8";
@interface ViewController () <IMAAdsLoaderDelegate, IMAStreamManagerDelegate>

...

- (void)requestStream {
    // Create an ad display container for ad rendering.
    IMAAdDisplayContainer *adDisplayContainer =
        [[IMAAdDisplayContainer alloc] initWithAdContainer:self.videoView
                                            viewController:self
                                            companionSlots:nil];
    // Create an IMAAVPlayerVideoDisplay to give the SDK access to your video player.
    IMAAVPlayerVideoDisplay *imaVideoDisplay =
        [[IMAAVPlayerVideoDisplay alloc] initWithAVPlayer:self.contentPlayer];
    IMAVideoStitcherVODStreamRequest *streamRequest =
        [[IMAVideoStitcherVODStreamRequest alloc] initWithVODConfigID:kVODConfigID
                                                             region:kLocation
                                                      projectNumber:kProjectNumber
                                                         OAuthToken:kOAuthToken
                                                        networkCode:kNetworkCode
                                                 adDisplayContainer:adDisplayContainer
                                                       videoDisplay:imaVideoDisplay
                                                        userContext:nil
                                        videoStitcherSessionOptions:nil];
    [self.adsLoader requestStreamWithRequest:streamRequest];
}

...

Swift

ViewController.swift

...

class ViewController: UIViewController, IMAAdsLoaderDelegate, IMAStreamManagerDelegate {
  /// The Stream's VOD config ID.
  static let vodConfigID = "VOD_CONFIG_ID"
  /// The Network Code used by the Video Stitcher API.
  static let networkCode = "NETWORK_CODE"
  /// The Google Cloud project using the Video Stitcher API.
  static let projectNumber = "PROJECT_NUMBER"
  /// The Google Cloud region containing your project.
  static let location = "LOCATION"
  /// An OAuth Token created by a Google Cloud account with Video Stitcher API
  /// permissions.
  static let oAuthToken = "OAUTH_TOKEN"

  /// Fallback URL in case something goes wrong in loading the stream. If all goes well, this will
  /// not be used.
  static let backupStreamURLString = """
    http://googleimadev-vh.akamaihd.net/i/big_buck_bunny/\
    bbb-,480p,720p,1080p,.mov.csmil/master.m3u8
    """

  ...

  func requestStream() {
    // Create an ad display container for ad rendering.
    adDisplayContainer = IMAAdDisplayContainer(
      adContainer: videoView,
      viewController: self,
      companionSlots: nil)
    // Create an IMAAVPlayerVideoDisplay to give the SDK access to your video player.
    let imaVideoDisplay = IMAAVPlayerVideoDisplay(avPlayer: contentPlayer!)
    // Create a VOD stream request.
    let streamRequest = IMAVideoStitcherVODStreamRequest(
      VODConfigID: ViewController.vodConfigID,
      region: ViewController.location,
      projectNumber: ViewController.projectNumber,
      oAuthToken: ViewController.oAuthToken,
      networkCode: ViewController.networkCode,
      adDisplayContainer: adDisplayContainer!,
      videoDisplay: imaVideoDisplay,
      userContext: nil,
      videoStitcherSessionOptions: nil)
    adsLoader?.requestStream(with: streamRequest)
  }

  ...

프로젝트를 실행하면 커스텀 VOD 스트림을 요청하고 재생할 수 있습니다.

(선택사항) 스트리밍 세션 옵션 추가

IMAVideoStitcherVODStreamRequestvideoStitcherSessionOptions 매개변수를 채워 기본 Cloud Video Stitcher API 구성을 재정의하는 세션 옵션을 추가하여 스트림 요청을 맞춤설정합니다. 인식할 수 없는 옵션을 제공하면 Cloud Video Stitcher API에서 HTTP 400 오류로 응답합니다. 도움이 필요하면 문제 해결 가이드를 참조하세요.

예를 들어 다음 코드 스니펫으로 매니페스트 옵션을 재정의할 수 있으며 이 옵션에서는 가장 낮은 비트 전송률에서 가장 높은 비트 전송률 순으로 변환되는 스트림 매니페스트 2개를 요청합니다.

Objective-C

 // define session options JSON string
 NSString *sessionOptionsStr =
   @"{"
   "  \"manifestOptions\": {"
   "    \"includeRenditions\":["
   "      {\"bitrateBps\": 3000, \"codecs\": \"hvc1.1.4.L126.B0, mp4a.40.2\"},"
   "      {\"bitrateBps\": 2000, \"codecs\": \"avc1.64001f, mp4a.40.2\"},"
   "    ]"
   "  }"
   "}";
 // convert JSON NSString to NSDictionary
 NSData *sessionOptionsData = [sessionOptionsStr dataUsingEncoding:NSUTF8StringEncoding];
 NSError *error = nil;
 NSDictionary *sessionOptions = [NSJSONSerialization
                       JSONObjectWithData:sessionOptionsData
                       options:0
                       error:&error];
 // make stream request
 IMAVideoStitcherVODStreamRequest *streamRequest =
     [[IMAVideoStitcherVODStreamRequest alloc] initWithVODConfigID:kVODConfigId
                                                           region:kRegion
                                                     projectNumber:kProjectNumber
                                                       OAuthToken:kOAuthToken
                                                       networkCode:kNetworkCode
                                               adDisplayContainer:adDisplayContainer
                                                     videoDisplay:imaVideoDisplay
                                                       userContext:nil
                                       videoStitcherSessionOptions:sessionOptions];
 [self.adsLoader requestStreamWithRequest:streamRequest];

Swift

 // define session options JSON string
 let sessionOptionsStr = """
     {
       "manifestOptions": {
         "includeRenditions": [
           {"bitrateBps": 3000, "codecs": "hvc1.1.4.L126.B0, mp4a.40.2"},
           {"bitrateBps": 2000, "codecs": "avc1.64001f, mp4a.40.2"},
         ],
         "bitrateOrder": "ascending"
       }
     }
     """
 // convert JSON string to dictionary
 guard let sessionOptionsData = sessionOptionsStr.data(using: .utf8, allowLossyConversion: false) else { return nil }
 let sessionOptions = try? JSONSerialization.jsonObject(with: sessionOptionsData, options: .mutableContainers)
 // make stream request
 let streamRequest = IMAVideoStitcherVODStreamRequest(
   vodConfigID:ViewController.vodConfigID
   region:ViewController.region
   projectNumber:ViewController.projectNumber
   OAuthToken:ViewController.oAuthToken
   networkCode:ViewController.networkCode
   adDisplayContainer:adDisplayContainer
   videoDisplay:imaVideoDisplay
   userContext:nil
   videoStitcherSessionOptions:sessionOptions)
 adsLoader?.requestStream(with: streamRequest)

삭제

이제 Google Cloud Video Stitcher API를 사용하여 VOD 스트림을 성공적으로 호스팅하고 iOS용 IMA DAI SDK를 사용하여 요청했으므로 모든 제공 리소스를 삭제해야 합니다.

VOD 삭제 가이드에 따라 불필요한 리소스와 애셋을 삭제합니다.