Cast を iOS アプリに統合する

コレクションでコンテンツを整理 必要に応じて、コンテンツの保存と分類を行います。

このデベロッパー ガイドでは、iOS Sender SDK を使用して iOS 送信者アプリに Google Cast サポートを追加する方法について説明します。

モバイル デバイスやノートパソコンは再生元のセンダーであり、Google Cast デバイスは、テレビにコンテンツを表示するレシーバです。

送信者フレームワークとは、実行時に送信側に存在するキャスト クラス ライブラリ バイナリと関連リソースを指します。送信者アプリまたはキャストアプリは、同じく送信者で実行されているアプリを指します。ウェブ レシーバ アプリは、ウェブ レシーバで実行されている HTML アプリケーションを指します。

送信者のフレームワークは、非同期コールバック設計を使用して、送信者アプリにイベントを通知するとともに、キャストアプリのライフサイクルのさまざまな状態を遷移します。

アプリケーションの流れ

次に、送信者の iOS アプリの一般的な実行フローについて説明します。

  • キャスト フレームワークは、GCKCastOptions で指定されたプロパティに基づいて GCKDiscoveryManager を開始し、デバイスのスキャンを開始します。
  • ユーザーがキャスト ボタンをクリックすると、フレームワークにより、検出されたキャスト デバイスのリストを含むキャスト ダイアログが表示されます。
  • ユーザーがキャスト デバイスを選択すると、フレームワークはキャスト デバイスで Web Receiver アプリを起動しようとします。
  • フレームワークは、送信側アプリでコールバックを呼び出し、Web Receiver アプリが起動されたことを確認します。
  • フレームワークは、送信者アプリと Web Receiver アプリ間の通信チャネルを作成します。
  • フレームワークは、通信チャネルを使用して、ウェブ レシーバーでのメディア再生の読み込みと制御を行います。
  • フレームワークは、送信側と Web Receiver の間でメディアの再生状態を同期します。ユーザーが送信側の UI アクションを実行すると、フレームワークはメディア制御リクエストをウェブ受信側に渡し、ウェブレシーバーがメディアのステータスの更新を送信すると、フレームワークは送信側の UI の状態を更新します。
  • ユーザーがキャスト アイコンをクリックしてキャスト デバイスから切断すると、フレームワークは送信者アプリをウェブレシーバーから切断します。

送信者のトラブルシューティングを行うには、ロギングを有効にする必要があります。

Google Cast iOS フレームワークのすべてのクラス、メソッド、イベントの一覧については、Google Cast iOS API リファレンスをご覧ください。以下のセクションでは、iOS アプリに Cast を統合する手順について説明します。

メインスレッドからメソッドを呼び出す

キャスト コンテキストを初期化する

キャスト フレームワークには、フレームワークのすべてのアクティビティを調整するグローバル シングルトン オブジェクト GCKCastContext があります。このオブジェクトは、アプリのライフサイクルの初期(通常はアプリのデリゲートの -[application:didFinishLaunchingWithOptions:] メソッド)で初期化する必要があります。これにより、送信者のアプリの再起動時に自動的にセッションが再開されます。

GCKCastOptions オブジェクトは、GCKCastContext を初期化するときに指定する必要があります。このクラスには、フレームワークの動作に影響を与えるオプションが含まれています。最も重要なのは Web Receiver アプリケーション ID です。ID を使用して検出結果をフィルタし、キャスト セッションの開始時に Web Receiver アプリを起動します。

また、-[application:didFinishLaunchingWithOptions:] メソッドは、フレームワークからロギング メッセージを受信するようにロギング デリゲートを設定するのに適しています。これらはデバッグとトラブルシューティングに役立ちます。

Swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GCKLoggerDelegate {
  let kReceiverAppID = kGCKDefaultMediaReceiverApplicationID
  let kDebugLoggingEnabled = true

  var window: UIWindow?

  func applicationDidFinishLaunching(_ application: UIApplication) {
    let criteria = GCKDiscoveryCriteria(applicationID: kReceiverAppID)
    let options = GCKCastOptions(discoveryCriteria: criteria)
    GCKCastContext.setSharedInstanceWith(options)

    // Enable logger.
    GCKLogger.sharedInstance().delegate = self

    ...
  }

  // MARK: - GCKLoggerDelegate

  func logMessage(_ message: String,
                  at level: GCKLoggerLevel,
                  fromFunction function: String,
                  location: String) {
    if (kDebugLoggingEnabled) {
      print(function + " - " + message)
    }
  }
}
Objective-C

AppDelegate.h

@interface AppDelegate () <GCKLoggerDelegate>
@end

AppDelegate.m

@implementation AppDelegate

static NSString *const kReceiverAppID = @"AABBCCDD";
static const BOOL kDebugLoggingEnabled = YES;

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  GCKDiscoveryCriteria *criteria = [[GCKDiscoveryCriteria alloc]
                                    initWithApplicationID:kReceiverAppID];
  GCKCastOptions *options = [[GCKCastOptions alloc] initWithDiscoveryCriteria:criteria];
  [GCKCastContext setSharedInstanceWithOptions:options];

  // Enable logger.
  [GCKLogger sharedInstance].delegate = self;

  ...

  return YES;
}

...

#pragma mark - GCKLoggerDelegate

- (void)logMessage:(NSString *)message
           atLevel:(GCKLoggerLevel)level
      fromFunction:(NSString *)function
          location:(NSString *)location {
  if (kDebugLoggingEnabled) {
    NSLog(@"%@ - %@, %@", function, message, location);
  }
}

@end

キャスト UX ウィジェット

Cast iOS SDK には、キャスト デザイン チェックリストに準拠したウィジェットが用意されています。

  • スタートガイド オーバーレイ: GCKCastContext クラスには、presentCastInstructionsViewControllerOnceWithCastButton メソッドが用意されています。これを使用すると、ウェブ レシーバーを初めて使用する際にキャスト アイコンにスポットライトを当てることができます。送信者アプリは、テキスト、タイトル テキストの位置、閉じるボタンをカスタマイズできます。

  • キャスト アイコン: Cast iOS センダー SDK 4.6.0 以降では、送信デバイスが Wi-Fi に接続されると、キャスト アイコンが常に表示されます。ユーザーが最初にアプリの起動後にキャスト アイコンをタップしたときに権限ダイアログが表示されるので、ユーザーはアプリのローカル ネットワークへのアクセス権をネットワーク上のデバイスに付与できます。その後、ユーザーがキャスト アイコンをタップすると、検出されたデバイスを一覧表示するキャスト ダイアログが表示されます。デバイスが接続されている間にキャスト アイコンをタップすると、現在のメディア メタデータ(タイトル、レコーディング スタジオの名前、サムネイル画像など)が表示されるか、ユーザーはキャスト デバイスとの接続を解除できます。利用可能なデバイスがないときにユーザーがキャストボタンをタップすると、デバイスが見つからない理由とトラブルシューティングの方法を示す画面が表示されます。

  • ミニ コントローラ: ユーザーがコンテンツをキャストしていて、現在のコンテンツ ページや拡張コントローラから送信側アプリの別の画面に移動した場合、画面の下部にミニ コントローラが表示され、現在キャストされているメディア メタデータの確認や再生の制御が可能になります。

  • 拡張コントローラ: ユーザーがコンテンツをキャストしているときにメディア通知またはミニ コントローラをクリックすると、拡張コントローラが起動し、現在再生中のメディア メタデータが表示されます。また、メディア再生を制御する複数のボタンが表示されます。

キャスト アイコンを追加する

フレームワークはキャスト アイコン コンポーネントを UIButton サブクラスとして提供します。アプリのタイトルバーに追加するには、UIBarButtonItem でラップします。一般的な UIViewController サブクラスは、次のようにキャスト ボタンをインストールできます。

Swift
let castButton = GCKUICastButton(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
castButton.tintColor = UIColor.gray
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: castButton)
Objective-C
GCKUICastButton *castButton = [[GCKUICastButton alloc] initWithFrame:CGRectMake(0, 0, 24, 24)];
castButton.tintColor = [UIColor grayColor];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:castButton];

デフォルトでは、ボタンをタップすると、フレームワークが提供するキャスト ダイアログが開きます。

GCKUICastButton をストーリーボードに直接追加することもできます。

デバイスの検出を構成する

このフレームワークでは、デバイスが自動的に検出されます。カスタム UI を実装しない限り、検出プロセスを明示的に開始または停止する必要はありません。

フレームワーク内の検出は、GCKCastContext のプロパティである GCKDiscoveryManager クラスによって管理されます。フレームワークは、デバイスの選択と制御用にデフォルトのキャスト ダイアログ コンポーネントを提供します。デバイスリストは、デバイスにわかりやすい名前順に並べられます。

セッション管理の仕組み

Cast SDK のコンセプトは、キャスト セッションのコンセプトを導入したものです。このセッションでは、デバイスへの接続、Web Receiver アプリの起動(または参加)、アプリへの接続、メディア制御チャネルの初期化のステップが組み合わされます。キャスト セッションとウェブレシーバーのライフサイクルについて詳しくは、ウェブレシーバーのアプリケーション ライフサイクル ガイドをご覧ください。

セッションは、GCKCastContext のプロパティである GCKSessionManager クラスによって管理されます。個々のセッションは、クラス GCKSession のサブクラスで表されます。たとえば、GCKCastSession はキャスト デバイスとのセッションを表します。現在アクティブなキャスト セッション(ある場合)には、GCKSessionManagercurrentCastSession プロパティとしてアクセスできます。

GCKSessionManagerListener インターフェースを使用すると、セッションの作成、停止、再開、終了などのセッション イベントをモニタリングできます。フレームワークは、送信側アプリがバックグラウンドに移行するとセッションを自動的に停止し、アプリがフォアグラウンドに戻ると(または、セッションがアクティブな間に異常または異常なアプリ終了後に再起動されるように)セッションを再開しようとします。

キャスト ダイアログが使用されている場合は、ユーザーの操作に応じてセッションが作成され、自動的に破棄されます。それ以外の場合、アプリは GCKSessionManager のメソッドを使用して、セッションを明示的に開始および終了できます。

アプリがセッション ライフサイクル イベントに応じて特別な処理を行う必要がある場合、1 つ以上の GCKSessionManagerListener インスタンスを GCKSessionManager に登録できます。GCKSessionManagerListener は、セッションの開始、終了などのイベントのコールバックを定義するプロトコルです。

ストリーミング転送

セッション状態の保持はストリーム転送の基礎であり、ユーザーは音声コマンド、Google Home アプリ、スマートディスプレイを使用して既存の音声ストリームや動画ストリームをデバイス間で移動できます。メディアは、あるデバイス(ソース)で再生を停止し、別のデバイス(宛先)で再生を続けます。最新のファームウェアを搭載したキャスト デバイスは、ストリーミング転送のソースまたは宛先として機能します。

ストリーム転送中に新しい宛先デバイスを取得するには、[sessionManager:didResumeCastSession:] コールバック中に GCKCastSession#device プロパティを使用します。

詳細については、Web Receiver でのストリーム転送をご覧ください。

自動再接続

キャスト フレームワークには、再接続ロジックを追加して、以下のような微妙な特殊な場合に再接続を自動的に処理できます。

  • Wi-Fi の一時的な復旧から復旧する
  • デバイスの睡眠から回復
  • アプリをバックグラウンドから復元する
  • アプリがクラッシュした場合に復元する

メディア コントロールの仕組み

メディア名前空間をサポートするウェブ レシーバ アプリでキャスト セッションが確立されている場合、GCKRemoteMediaClient のインスタンスはフレームワークによって自動的に作成されます。このインスタンスは、GCKCastSession インスタンスの remoteMediaClient プロパティとしてアクセスできます。

ウェブレシーバーにリクエストを発行する GCKRemoteMediaClient のすべてのメソッドは、そのリクエストの追跡に使用できる GCKRequest オブジェクトを返します。このオブジェクトに GCKRequestDelegate を割り当てて、オペレーションの結果に関する通知を受け取ることができます。

GCKRemoteMediaClient のインスタンスはアプリの複数の部分で共有される可能性があり、キャスト ダイアログやミニメディア コントロールなど、フレームワークの内部コンポーネントもインスタンスを共有します。そのため、GCKRemoteMediaClient は複数の GCKRemoteMediaClientListener の登録をサポートしています。

メディア メタデータを設定する

GCKMediaMetadata クラスは、キャストするメディア アイテムに関する情報を表します。次の例では、映画の新しい GCKMediaMetadata インスタンスを作成し、タイトル、サブタイトル、録音スタジオの名前、2 つの画像を設定しています。

Swift
let metadata = GCKMediaMetadata()
metadata.setString("Big Buck Bunny (2008)", forKey: kGCKMetadataKeyTitle)
metadata.setString("Big Buck Bunny tells the story of a giant rabbit with a heart bigger than " +
  "himself. When one sunny day three rodents rudely harass him, something " +
  "snaps... and the rabbit ain't no bunny anymore! In the typical cartoon " +
  "tradition he prepares the nasty rodents a comical revenge.",
                   forKey: kGCKMetadataKeySubtitle)
metadata.addImage(GCKImage(url: URL(string: "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg")!,
                           width: 480,
                           height: 360))
Objective-C
GCKMediaMetadata *metadata = [[GCKMediaMetadata alloc]
                                initWithMetadataType:GCKMediaMetadataTypeMovie];
[metadata setString:@"Big Buck Bunny (2008)" forKey:kGCKMetadataKeyTitle];
[metadata setString:@"Big Buck Bunny tells the story of a giant rabbit with a heart bigger than "
 "himself. When one sunny day three rodents rudely harass him, something "
 "snaps... and the rabbit ain't no bunny anymore! In the typical cartoon "
 "tradition he prepares the nasty rodents a comical revenge."
             forKey:kGCKMetadataKeySubtitle];
[metadata addImage:[[GCKImage alloc]
                    initWithURL:[[NSURL alloc] initWithString:@"https://commondatastorage.googleapis.com/"
                                 "gtv-videos-bucket/sample/images/BigBuckBunny.jpg"]
                    width:480
                    height:360]];

メディア メタデータを含む画像の使用については、画像の選択とキャッシュのセクションをご覧ください。

メディアを読み込む

メディア アイテムを読み込むには、メディア メタデータを使用して GCKMediaInformation インスタンスを作成します。次に、現在の GCKCastSession を取得し、その GCKRemoteMediaClient を使用して、レシーバ アプリにメディアを読み込みます。レシーバで実行されているメディア プレーヤー アプリ(再生、一時停止、停止など)を制御するには、GCKRemoteMediaClient を使用します。

Swift
let url = URL.init(string: "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4")
guard let mediaURL = url else {
  print("invalid mediaURL")
  return
}

let mediaInfoBuilder = GCKMediaInformationBuilder.init(contentURL: mediaURL)
mediaInfoBuilder.streamType = GCKMediaStreamType.none;
mediaInfoBuilder.contentType = "video/mp4"
mediaInfoBuilder.metadata = metadata;
mediaInformation = mediaInfoBuilder.build()

guard let mediaInfo = mediaInformation else {
  print("invalid mediaInformation")
  return
}

if let request = sessionManager.currentSession?.remoteMediaClient?.loadMedia(mediaInfo) {
  request.delegate = self
}
Objective-C
GCKMediaInformationBuilder *mediaInfoBuilder =
  [[GCKMediaInformationBuilder alloc] initWithContentURL:
   [NSURL URLWithString:@"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"]];
mediaInfoBuilder.streamType = GCKMediaStreamTypeNone;
mediaInfoBuilder.contentType = @"video/mp4";
mediaInfoBuilder.metadata = metadata;
self.mediaInformation = [mediaInfoBuilder build];

GCKRequest *request = [self.sessionManager.currentSession.remoteMediaClient loadMedia:self.mediaInformation];
if (request != nil) {
  request.delegate = self;
}

メディア トラックの使用に関するセクションもご覧ください。

4K 動画形式

メディアの動画形式を判別するには、GCKMediaStatusvideoInfo プロパティを使用して GCKVideoInfo の現在のインスタンスを取得します。このインスタンスには、HDR TV の形式の種類と高さと幅(ピクセル単位)が含まれています。4K 形式のバリアントは、hdrType プロパティの列挙値 GCKVideoInfoHDRType で示されます。

ミニ コントローラの追加

キャスト デザイン チェックリストによると、送信側アプリは、ユーザーが現在のコンテンツ ページから移動したときに表示されるミニ コントローラと呼ばれる永続的なコントロールを提供する必要があります。ミニ コントローラを使用すると、すぐにアクセスでき、現在のキャスト セッションにリマインダーが表示されます。

キャスト フレームワークにはコントロール バー GCKUIMiniMediaControlsViewController が用意されています。このコントロール バーは、ミニ コントローラを表示するシーンに追加できます。

送信側アプリが動画または音声のライブ ストリームを再生すると、ミニ コントローラの再生/一時停止ボタンの代わりに再生/停止ボタンが自動的に表示されます。

送信側アプリがキャスト ウィジェットの外観を設定する方法については、iOS の送信側 UI をカスタマイズするをご覧ください。

送信者アプリにミニ コントローラを追加するには、次の 2 つの方法があります。

  • 既存のビュー コントローラを独自のビュー コントローラでラップすることで、キャスト フレームワークがミニ コントローラのレイアウトを管理できるようにします。
  • ミニコントローラ ウィジェットのレイアウトは、ストーリーボードにサブビューを追加して既存のビュー コントローラに追加して、自分で管理できます。

GCKUICastContainerViewController を使用してラップする

1 つ目の方法は、別のビュー コントローラをラップし、下部に GCKUIMiniMediaControlsViewController を追加する GCKUICastContainerViewController を使用する方法です。このアプローチには、アニメーションをカスタマイズできず、コンテナビュー コントローラの動作を構成できないという制限があります。

この最初の方法は、通常、アプリのデリゲートの -[application:didFinishLaunchingWithOptions:] メソッドで行います。

Swift
func applicationDidFinishLaunching(_ application: UIApplication) {
  ...

  // Wrap main view in the GCKUICastContainerViewController and display the mini controller.
  let appStoryboard = UIStoryboard(name: "Main", bundle: nil)
  let navigationController = appStoryboard.instantiateViewController(withIdentifier: "MainNavigation")
  let castContainerVC =
          GCKCastContext.sharedInstance().createCastContainerController(for: navigationController)
  castContainerVC.miniMediaControlsItemEnabled = true
  window = UIWindow(frame: UIScreen.main.bounds)
  window!.rootViewController = castContainerVC
  window!.makeKeyAndVisible()

  ...
}
Objective-C
- (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  ...

  // Wrap main view in the GCKUICastContainerViewController and display the mini controller.
  UIStoryboard *appStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  UINavigationController *navigationController =
          [appStoryboard instantiateViewControllerWithIdentifier:@"MainNavigation"];
  GCKUICastContainerViewController *castContainerVC =
          [[GCKCastContext sharedInstance] createCastContainerControllerForViewController:navigationController];
  castContainerVC.miniMediaControlsItemEnabled = YES;
  self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
  self.window.rootViewController = castContainerVC;
  [self.window makeKeyAndVisible];
  ...

}
Swift
var castControlBarsEnabled: Bool {
  set(enabled) {
    if let castContainerVC = self.window?.rootViewController as? GCKUICastContainerViewController {
      castContainerVC.miniMediaControlsItemEnabled = enabled
    } else {
      print("GCKUICastContainerViewController is not correctly configured")
    }
  }
  get {
    if let castContainerVC = self.window?.rootViewController as? GCKUICastContainerViewController {
      return castContainerVC.miniMediaControlsItemEnabled
    } else {
      print("GCKUICastContainerViewController is not correctly configured")
      return false
    }
  }
}
Objective-C

AppDelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, assign) BOOL castControlBarsEnabled;

@end

AppDelegate.m

@implementation AppDelegate

...

- (void)setCastControlBarsEnabled:(BOOL)notificationsEnabled {
  GCKUICastContainerViewController *castContainerVC;
  castContainerVC =
      (GCKUICastContainerViewController *)self.window.rootViewController;
  castContainerVC.miniMediaControlsItemEnabled = notificationsEnabled;
}

- (BOOL)castControlBarsEnabled {
  GCKUICastContainerViewController *castContainerVC;
  castContainerVC =
      (GCKUICastContainerViewController *)self.window.rootViewController;
  return castContainerVC.miniMediaControlsItemEnabled;
}

...

@end

既存のビュー コントローラに埋め込む

2 つ目の方法は、createMiniMediaControlsViewController を使用して GCKUIMiniMediaControlsViewController インスタンスを作成し、サブビューとしてコンテナビュー コントローラに追加することで、ミニコントローラを既存のビュー コントローラに直接追加することです。

アプリのデリゲートでビュー コントローラをセットアップします。

Swift
func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  ...

  GCKCastContext.sharedInstance().useDefaultExpandedMediaControls = true
  window?.clipsToBounds = true

  let rootContainerVC = (window?.rootViewController as? RootContainerViewController)
  rootContainerVC?.miniMediaControlsViewEnabled = true

  ...

  return true
}
Objective-C
- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  ...

  [GCKCastContext sharedInstance].useDefaultExpandedMediaControls = YES;

  self.window.clipsToBounds = YES;

  RootContainerViewController *rootContainerVC;
  rootContainerVC =
      (RootContainerViewController *)self.window.rootViewController;
  rootContainerVC.miniMediaControlsViewEnabled = YES;

  ...

  return YES;
}

ルートビュー コントローラで、GCKUIMiniMediaControlsViewController インスタンスを作成し、それをサブビューとしてコンテナビュー コントローラに追加します。

Swift
let kCastControlBarsAnimationDuration: TimeInterval = 0.20

@objc(RootContainerViewController)
class RootContainerViewController: UIViewController, GCKUIMiniMediaControlsViewControllerDelegate {
  @IBOutlet weak private var _miniMediaControlsContainerView: UIView!
  @IBOutlet weak private var _miniMediaControlsHeightConstraint: NSLayoutConstraint!
  private var miniMediaControlsViewController: GCKUIMiniMediaControlsViewController!
  var miniMediaControlsViewEnabled = false {
    didSet {
      if self.isViewLoaded {
        self.updateControlBarsVisibility()
      }
    }
  }

  var overriddenNavigationController: UINavigationController?

  override var navigationController: UINavigationController? {

    get {
      return overriddenNavigationController
    }

    set {
      overriddenNavigationController = newValue
    }
  }
  var miniMediaControlsItemEnabled = false

  override func viewDidLoad() {
    super.viewDidLoad()
    let castContext = GCKCastContext.sharedInstance()
    self.miniMediaControlsViewController = castContext.createMiniMediaControlsViewController()
    self.miniMediaControlsViewController.delegate = self
    self.updateControlBarsVisibility()
    self.installViewController(self.miniMediaControlsViewController,
                               inContainerView: self._miniMediaControlsContainerView)
  }

  func updateControlBarsVisibility() {
    if self.miniMediaControlsViewEnabled && self.miniMediaControlsViewController.active {
      self._miniMediaControlsHeightConstraint.constant = self.miniMediaControlsViewController.minHeight
      self.view.bringSubview(toFront: self._miniMediaControlsContainerView)
    } else {
      self._miniMediaControlsHeightConstraint.constant = 0
    }
    UIView.animate(withDuration: kCastControlBarsAnimationDuration, animations: {() -> Void in
      self.view.layoutIfNeeded()
    })
    self.view.setNeedsLayout()
  }

  func installViewController(_ viewController: UIViewController?, inContainerView containerView: UIView) {
    if let viewController = viewController {
      self.addChildViewController(viewController)
      viewController.view.frame = containerView.bounds
      containerView.addSubview(viewController.view)
      viewController.didMove(toParentViewController: self)
    }
  }

  func uninstallViewController(_ viewController: UIViewController) {
    viewController.willMove(toParentViewController: nil)
    viewController.view.removeFromSuperview()
    viewController.removeFromParentViewController()
  }

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "NavigationVCEmbedSegue" {
      self.navigationController = (segue.destination as? UINavigationController)
    }
  }

...
Objective-C

RootContainerViewController.h

static const NSTimeInterval kCastControlBarsAnimationDuration = 0.20;

@interface RootContainerViewController () <GCKUIMiniMediaControlsViewControllerDelegate> {
  __weak IBOutlet UIView *_miniMediaControlsContainerView;
  __weak IBOutlet NSLayoutConstraint *_miniMediaControlsHeightConstraint;
  GCKUIMiniMediaControlsViewController *_miniMediaControlsViewController;
}

@property(nonatomic, weak, readwrite) UINavigationController *navigationController;

@property(nonatomic, assign, readwrite) BOOL miniMediaControlsViewEnabled;
@property(nonatomic, assign, readwrite) BOOL miniMediaControlsItemEnabled;

@end

RootContainerViewController.m

@implementation RootContainerViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  GCKCastContext *castContext = [GCKCastContext sharedInstance];
  _miniMediaControlsViewController =
      [castContext createMiniMediaControlsViewController];
  _miniMediaControlsViewController.delegate = self;

  [self updateControlBarsVisibility];
  [self installViewController:_miniMediaControlsViewController
              inContainerView:_miniMediaControlsContainerView];
}

- (void)setMiniMediaControlsViewEnabled:(BOOL)miniMediaControlsViewEnabled {
  _miniMediaControlsViewEnabled = miniMediaControlsViewEnabled;
  if (self.isViewLoaded) {
    [self updateControlBarsVisibility];
  }
}

- (void)updateControlBarsVisibility {
  if (self.miniMediaControlsViewEnabled &&
      _miniMediaControlsViewController.active) {
    _miniMediaControlsHeightConstraint.constant =
        _miniMediaControlsViewController.minHeight;
    [self.view bringSubviewToFront:_miniMediaControlsContainerView];
  } else {
    _miniMediaControlsHeightConstraint.constant = 0;
  }
  [UIView animateWithDuration:kCastControlBarsAnimationDuration
                   animations:^{
                     [self.view layoutIfNeeded];
                   }];
  [self.view setNeedsLayout];
}

- (void)installViewController:(UIViewController *)viewController
              inContainerView:(UIView *)containerView {
  if (viewController) {
    [self addChildViewController:viewController];
    viewController.view.frame = containerView.bounds;
    [containerView addSubview:viewController.view];
    [viewController didMoveToParentViewController:self];
  }
}

- (void)uninstallViewController:(UIViewController *)viewController {
  [viewController willMoveToParentViewController:nil];
  [viewController.view removeFromSuperview];
  [viewController removeFromParentViewController];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  if ([segue.identifier isEqualToString:@"NavigationVCEmbedSegue"]) {
    self.navigationController =
        (UINavigationController *)segue.destinationViewController;
  }
}

...

@end

GCKUIMiniMediaControlsViewControllerDelegate は、ミニ コントローラを表示するタイミングをホストビュー コントローラに伝えます。

Swift
  func miniMediaControlsViewController(_: GCKUIMiniMediaControlsViewController,
                                       shouldAppear _: Bool) {
    updateControlBarsVisibility()
  }
Objective-C
- (void)miniMediaControlsViewController:
            (GCKUIMiniMediaControlsViewController *)miniMediaControlsViewController
                           shouldAppear:(BOOL)shouldAppear {
  [self updateControlBarsVisibility];
}

拡張コントローラを追加

Google Cast デザイン チェックリストでは、送信側アプリで、キャストするメディアに拡張コントローラを用意する必要があります。拡張コントローラは、ミニ コントローラのフルスクリーン バージョンです。

展開されたコントローラは、リモート メディア再生を完全に制御できる全画面ビューです。このビューにより、キャスト アプリはキャスト セッションのあらゆる管理可能な要素を管理できるようになります。ただし、Web Receiver の音量コントロールとセッションのライフサイクル(接続/停止)は除きます。また、メディア セッションに関するすべてのステータス情報(アートワーク、タイトル、サブタイトルなど)も表示されます。

このビューの機能は、GCKUIExpandedMediaControlsViewController クラスによって実装されます。

まず、キャスト コンテキストでデフォルトの拡張コントローラを有効にする必要があります。アプリのデリゲートを変更して、デフォルトの拡張コントローラを有効にします。

Swift
func applicationDidFinishLaunching(_ application: UIApplication) {
  ..

  GCKCastContext.sharedInstance().useDefaultExpandedMediaControls = true

  ...
}
Objective-C
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  ...

  [GCKCastContext sharedInstance].useDefaultExpandedMediaControls = YES;

  ..
}

ユーザーが動画のキャストを開始したときに拡張コントローラを読み込むには、次のコードをビュー コントローラに追加します。

Swift
func playSelectedItemRemotely() {
  GCKCastContext.sharedInstance().presentDefaultExpandedMediaControls()

  ...

  // Load your media
  sessionManager.currentSession?.remoteMediaClient?.loadMedia(mediaInformation)
}
Objective-C
- (void)playSelectedItemRemotely {
  [[GCKCastContext sharedInstance] presentDefaultExpandedMediaControls];

  ...

  // Load your media
  [self.sessionManager.currentSession.remoteMediaClient loadMedia:mediaInformation];
}

また、ユーザーがミニ コントローラをタップすると、拡張コントローラが自動的に起動します。

送信側アプリが動画または音声のライブ ストリームを再生すると、拡張コントローラの再生/一時停止ボタンの代わりに、再生/停止ボタンが自動的に表示されます。

送信側アプリがキャスト ウィジェットの外観を設定する方法については、iOS アプリにカスタム スタイルを適用するをご覧ください。

音量調節

Cast フレームワークは、送信側アプリのボリュームを自動的に管理します。フレームワークは、提供された UI ウィジェットの Web Receiver ボリュームと自動的に同期します。アプリが提供するスライダーを同期するには、GCKUIDeviceVolumeController を使用します。

物理ボタンの音量コントロール

送信側のデバイスの物理音量ボタンを使用すると、GCKCastContext に設定されている GCKCastOptionsphysicalVolumeButtonsWillControlDeviceVolume フラグを使用して、ウェブレシーバーのキャスト セッションの音量を変更できます。

Swift
let criteria = GCKDiscoveryCriteria(applicationID: kReceiverAppID)
let options = GCKCastOptions(discoveryCriteria: criteria)
options.physicalVolumeButtonsWillControlDeviceVolume = true
GCKCastContext.setSharedInstanceWith(options)
Objective-C
GCKDiscoveryCriteria *criteria = [[GCKDiscoveryCriteria alloc]
                                          initWithApplicationID:kReceiverAppID];
GCKCastOptions *options = [[GCKCastOptions alloc]
                                          initWithDiscoveryCriteria :criteria];
options.physicalVolumeButtonsWillControlDeviceVolume = YES;
[GCKCastContext setSharedInstanceWithOptions:options];

エラーを処理する

送信者のアプリは、すべてのエラー コールバックを処理し、キャストのライフサイクルの各ステージに最適な応答を決定する必要があります。アプリでエラー ダイアログをユーザーに表示したり、キャスト セッションを終了したりできます。

ロギング

GCKLogger は、フレームワークによるロギングに使用されるシングルトンです。GCKLoggerDelegate を使用して、ログメッセージの処理方法をカスタマイズします。

SDK を使用すると、GCKLogger はデバッグ メッセージ、エラー、警告の形式でロギング出力を生成します。これらのログメッセージはデバッグをサポートし、問題のトラブルシューティングと特定に役立ちます。デフォルトではログ出力は抑制されますが、GCKLoggerDelegate を割り当てると、送信者のアプリは SDK からこれらのメッセージを受け取り、システム コンソールにログを記録できます。

Swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GCKLoggerDelegate {
  let kReceiverAppID = kGCKDefaultMediaReceiverApplicationID
  let kDebugLoggingEnabled = true

  var window: UIWindow?

  func applicationDidFinishLaunching(_ application: UIApplication) {
    ...

    // Enable logger.
    GCKLogger.sharedInstance().delegate = self

    ...
  }

  // MARK: - GCKLoggerDelegate

  func logMessage(_ message: String,
                  at level: GCKLoggerLevel,
                  fromFunction function: String,
                  location: String) {
    if (kDebugLoggingEnabled) {
      print(function + " - " + message)
    }
  }
}
Objective-C

AppDelegate.h

@interface AppDelegate () <GCKLoggerDelegate>
@end

AppDelegate.m

@implementation AppDelegate

static NSString *const kReceiverAppID = @"AABBCCDD";
static const BOOL kDebugLoggingEnabled = YES;

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  ...

  // Enable logger.
  [GCKLogger sharedInstance].delegate = self;

  ...

  return YES;
}

...

#pragma mark - GCKLoggerDelegate

- (void)logMessage:(NSString *)message
           atLevel:(GCKLoggerLevel)level
      fromFunction:(NSString *)function
          location:(NSString *)location {
  if (kDebugLoggingEnabled) {
    NSLog(@"%@ - %@, %@", function, message, location);
  }
}

@end

デバッグ メッセージと詳細メッセージも有効にするには、委譲を設定した後、前述の行をコードに追加します(上記を参照)。

Swift
let filter = GCKLoggerFilter.init()
filter.minimumLevel = GCKLoggerLevel.verbose
GCKLogger.sharedInstance().filter = filter
Objective-C
GCKLoggerFilter *filter = [[GCKLoggerFilter alloc] init];
[filter setMinimumLevel:GCKLoggerLevelVerbose];
[GCKLogger sharedInstance].filter = filter;

GCKLogger によって生成されたログメッセージをフィルタリングすることもできます。クラスごとに最小ロギングレベルを設定します。次に例を示します。

Swift
let filter = GCKLoggerFilter.init()
filter.setLoggingLevel(GCKLoggerLevel.verbose, forClasses: ["GCKUICastButton",
                                                            "GCKUIImageCache",
                                                            "NSMutableDictionary"])
GCKLogger.sharedInstance().filter = filter
Objective-C
GCKLoggerFilter *filter = [[GCKLoggerFilter alloc] init];
[filter setLoggingLevel:GCKLoggerLevelVerbose
             forClasses:@[@"GCKUICastButton",
                          @"GCKUIImageCache",
                          @"NSMutableDictionary"
                          ]];
[GCKLogger sharedInstance].filter = filter;

クラス名は、リテラル名または glob パターンのいずれかです(例: GCKUI\*GCK\*Session)。