支援投放功能的 iOS 應用程式

1. 總覽

Google Cast 標誌

本程式碼研究室將說明如何修改現有的 iOS 影片應用程式,以便將內容投放至支援 Google Cast 的裝置。

什麼是 Google Cast?

Google Cast 可讓使用者將行動裝置上的內容投放到電視。使用者就能使用行動裝置當作遙控器,在電視上播放媒體。

Google Cast SDK 可讓您擴充應用程式,控制支援 Google Cast 的裝置 (例如電視或音響系統)。Cast SDK 可讓您根據 Google Cast 設計檢查清單新增必要的 UI 元件。

我們提供了 Google Cast 設計檢查清單,大幅簡化所有支援平台的 Cast 使用者體驗,並讓使用者享有簡單預測。

我們要建構什麼?

完成本程式碼研究室後,您將擁有一個 iOS 影片應用程式,可將影片投放至 Google Cast 裝置。

課程內容

  • 如何將 Google Cast SDK 新增至範例影片應用程式。
  • 如何新增「投放」按鈕以選取 Google Cast 裝置。
  • 如何連線至投放裝置並啟動媒體接收器。
  • 如何投放影片。
  • 如何在應用程式中新增 Cast mini 控制器。
  • 如何新增展開控制器。
  • 如何提供簡介重疊廣告。
  • 如何自訂投放小工具。
  • 如何整合 Cast Connect

軟硬體需求

  • 最新的 Xcode
  • 一部搭載 iOS 9 以上版本的行動裝置 (或 Xcode 模擬器)。
  • USB 傳輸線,用於將行動裝置連接至開發電腦 (如果使用裝置)。
  • Google Cast 裝置,例如已設定連上網際網路的 ChromecastAndroid TV
  • 具備 HDMI 輸入端的電視或螢幕。
  • 你必須使用 Chromecast (支援 Google TV),才能測試 Cast Connect 整合作業,但對於程式碼研究室的其他部分,你可以選擇是否使用。如果您沒有裝置,可在本教學課程結尾略過「新增 Cast Connect 支援」步驟。

體驗

  • 請注意,您必須具備過往的 iOS 開發知識,
  • 你也需要事先瞭解看電視的知識 :)

您會如何使用這個教學課程?

只閱讀 閱讀並完成練習

您���建構 iOS 應用程式的體驗評價為何?

新手 中級 還算容易

你對觀看電視的體驗有什麼評價?

新手 中級 還算容易

2. 取得程式碼範例

您可以將所有程式碼範例下載至電腦...

然後將下載的 ZIP 檔案解壓縮。

3. 執行範例應用程式

Apple iOS 標誌

首先,我們來看看完成的範例應用程式是什麼樣子。這款應用程式是基本的影片播放器。使用者可以從清單中選取影片,然後在裝置上播放影片,或將影片投放至 Google Cast 裝置。

下載程式碼後,下列指示說明如何在 Xcode 中開啟及執行已完成的範例應用程式:

常見問題

CocoaPods 設定

如要設定 CocoaPods,請前往控制台,並使用 macOS 提供的預設 Ruby 進行安裝:

sudo gem install cocoapods

如有任何問題,請參閱官方說明文件,下載並安裝依附元件管理員。

專案設定

  1. 前往終端機,然後前往程式碼研究室目錄。
  2. 從 Podfile 安裝依附元件。
cd app-done
pod update
pod install
  1. 開啟 Xcode 並選取「Open another project...」
  2. 從範例程式碼資料夾中的 「資料夾」圖示app-done 目錄選取 CastVideos-ios.xcworkspace 檔案。

執行應用程式

選取目標和模擬器,然後執行應用程式:

XCode 應用程式模擬器工具列

影片應用程式應該會在幾秒後顯示。

請務必點選「允許」出現關於接受傳入網路連線的通知時。如未接受這個選項,就不會顯示「投放」圖示。

要求接受內送網路連線的確認對話方塊

按一下「投放」按鈕,然後選取你的 Google Cast 裝置。

選取影片,按一下播放按鈕。

影片就會開始在 Google Cast 裝置上播放。

畫面隨即顯示展開的控制器。您可以使用播放/暫停按鈕控製播放。

返回影片清單。

螢幕底部現在會顯示迷你控制器。

顯示執行 CastVideos 應用程式的 iPhone 插圖,下方有迷你控制器顯示在底部

按一下迷你控制器中的暫停按鈕,即可暫停接收端的影片。按一下迷你控制器中的「播放」按鈕,即可繼續播放影片。

按一下「投放」按鈕,即可停止將內容投放到 Google Cast 裝置。

4. 準備 start 專案

插圖:執行 CastVideos 應用程式的 iPhone

系統會在您下載的啟動應用程式中新增 Google Cast 支援功能。以下是本程式碼研究室將使用的 Google Cast 術語:

  • 寄件者應用程式是在行動裝置或筆記型電腦上執行
  • 接收器應用程式是在 Google Cast 裝置上執行。

專案設定

現在,您可以使用 Xcode 在範例專案上進行建構:

  1. 前往終端機,然後前往程式碼研究室目錄。
  2. 從 Podfile 安裝依附元件。
cd app-start
pod update
pod install
  1. 開啟 Xcode 並選取「Open another project...」
  2. 從範例程式碼資料夾中的 「資料夾」圖示app-start 目錄選取 CastVideos-ios.xcworkspace 檔案。

應用程式設計

應用程式會從遠端網路伺服器擷取影片清單,並提供使用者瀏覽清單。使用者可以選取影片來查看詳細資料,也可以在行動裝置上播放影片。

這個應用程式包含兩個主要的檢視畫面控制器:MediaTableViewControllerMediaViewController.

MediaTableViewController

這個 UITableViewController 會顯示 MediaListModel 執行個體中的影片清單。影片清單和相關聯的中繼資料會以 JSON 檔案的形式託管於遠端伺服器。MediaListModel 會擷取並處理這個 JSON,以建構 MediaItem 物件清單。

MediaItem 物件會為影片及其相關中繼資料建立模型,例如影片的標題、說明、圖片網址和串流網址。

MediaTableViewController 會建立 MediaListModel 例項,然後將自身註冊為 MediaListModelDelegate,以便在媒體中繼資料下載完成時收到通知,進而載入表格檢視畫面。

系統會向使用者顯示影片縮圖清單,以及每部影片的簡短說明。選取項目後,系統會將對應的 MediaItem 傳遞至 MediaViewController

MediaViewController

這個檢視控制器會顯示特定影片的中繼資料,並讓使用者透過行動裝置本機播放影片。

這個 View Controller 會代管 LocalPlayerView、部分媒體控制項,以及顯示所選影片說明的文字區域。播放器會覆蓋螢幕頂端,並在使用者下方保留影片詳細說明,以供播放/暫停,或尋找本機影片播放。

常見問題

5. 新增「投放」按鈕

插圖:執行 CastVideos 應用程式的 iPhone 頂端三分之一,右上角顯示「投放」按鈕

支援 Cast 的應用程式會在每個檢視控制器中顯示「投放」按鈕。按一下「投放」按鈕,系統會顯示投放裝置清單,供使用者選取。如果使用者在傳送端裝置上播放內容,選取投放裝置就會在該投放裝置上開始或繼續播放內容。在投放工作階段期間,使用者隨時可以按一下「投放」按鈕,停止將應用程式投放到投放裝置。如同 Google Cast 設計檢查清單中所述,使用者必須能在應用程式的任何畫面中連線或中斷與投放裝置的連線。

設定

啟動專案需要的依附元件和 Xcode 設定,與完成的範例應用程式相同。請返回該部分,按照相同步驟將 GoogleCast.framework 新增至啟動應用程式專案。

初始化

Cast 架構具有全域單例模式物件 GCKCastContext,用來協調所有架構的活動。這個物件必須在應用程式生命週期的早期初始化 (通常是應用程式委派的 application(_:didFinishLaunchingWithOptions:) 方法中),如此一來,傳送方應用程式重新啟動時的自動恢復工作階段即可正確觸發,並可開始掃描裝置。

初始化 GCKCastContext 時必須提供 GCKCastOptions 物件。此類別包含會影響架構行為的選項。其中最重要的是接收器應用程式 ID,用來篩選 Cast 裝置探索結果,以及在投放工作階段啟動時啟動接收器應用程式。

application(_:didFinishLaunchingWithOptions:) 方法也很適合用來設定記錄委派,以便接收來自 Cast 架構的記錄訊息。很適合用於偵錯和疑難排解。

開發自己的支援 Cast 的應用程式時,您必須註冊成為 Cast 開發人員,然後為應用程式取得應用程式 ID。在本程式碼研究室中,我們將使用範例應用程式 ID。

將下列程式碼新增至 AppDelegate.swift,以便使用使用者預設值中的應用程式 ID 初始化 GCKCastContext,並為 Google Cast 架構新增記錄器:

import GoogleCast

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  fileprivate var enableSDKLogging = true

  ...

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

    ...
    let options = GCKCastOptions(discoveryCriteria: GCKDiscoveryCriteria(applicationID: kReceiverAppID))
    options.physicalVolumeButtonsWillControlDeviceVolume = true
    GCKCastContext.setSharedInstanceWith(options)

    window?.clipsToBounds = true
    setupCastLogging()
    ...
  }
  ...
  func setupCastLogging() {
    let logFilter = GCKLoggerFilter()
    let classesToLog = ["GCKDeviceScanner", "GCKDeviceProvider", "GCKDiscoveryManager", "GCKCastChannel",
                        "GCKMediaControlChannel", "GCKUICastButton", "GCKUIMediaController", "NSMutableDictionary"]
    logFilter.setLoggingLevel(.verbose, forClasses: classesToLog)
    GCKLogger.sharedInstance().filter = logFilter
    GCKLogger.sharedInstance().delegate = self
  }
}

...

// MARK: - GCKLoggerDelegate

extension AppDelegate: GCKLoggerDelegate {
  func logMessage(_ message: String,
                  at _: GCKLoggerLevel,
                  fromFunction function: String,
                  location: String) {
    if enableSDKLogging {
      // Send SDK's log messages directly to the console.
      print("\(location): \(function) - \(message)")
    }
  }
}

投放按鈕

現在 GCKCastContext 已完成初始化,我們需要新增「投放」按鈕,讓使用者能夠選取投放裝置。Cast SDK 提供名為 GCKUICastButton 的投放按鈕元件,做為 UIButton 子類別。您可以將其納入 UIBarButtonItem 中,以便新增至應用程式的標題列。我們需要將「投放」按鈕新增至 MediaTableViewControllerMediaViewController

將以下程式碼加入 MediaTableViewController.swiftMediaViewController.swift

import GoogleCast

@objc(MediaTableViewController)
class MediaTableViewController: UITableViewController, GCKSessionManagerListener,
  MediaListModelDelegate, GCKRequestDelegate {
  private var castButton: GCKUICastButton!
  ...
  override func viewDidLoad() {
    print("MediaTableViewController - viewDidLoad")
    super.viewDidLoad()

    ...
    castButton = GCKUICastButton(frame: CGRect(x: CGFloat(0), y: CGFloat(0),
                                               width: CGFloat(24), height: CGFloat(24)))
    // Overwrite the UIAppearance theme in the AppDelegate.
    castButton.tintColor = UIColor.white
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: castButton)

    ...
  }
  ...
}

接著,請在 MediaViewController.swift 中加入下列程式碼:

import GoogleCast

@objc(MediaViewController)
class MediaViewController: UIViewController, GCKSessionManagerListener, GCKRemoteMediaClientListener,
  LocalPlayerViewDelegate, GCKRequestDelegate {
  private var castButton: GCKUICastButton!
  ...
  override func viewDidLoad() {
    super.viewDidLoad()
    print("in MediaViewController viewDidLoad")
    ...
    castButton = GCKUICastButton(frame: CGRect(x: CGFloat(0), y: CGFloat(0),
                                               width: CGFloat(24), height: CGFloat(24)))
    // Overwrite the UIAppearance theme in the AppDelegate.
    castButton.tintColor = UIColor.white
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: castButton)

    ...
  }
  ...
}

現在請執行應用程式。你應該會在應用程式的導覽列中看到「投放」按鈕;點按該按鈕後,就會列出區域網路中的投放裝置。裝置探索功能是由「GCKCastContext」自動管理。選取你的投放裝置,範例接收器應用程式就會在投放裝置上載入。您可以在瀏覽活動和本機播放器活動之間進行瀏覽,而「投放」按鈕狀態會保持同步。

我們尚未新增任何媒體播放支援功能,因此目前無法在投放裝置上播放影片。按一下「投放」按鈕即可停止投放。

6. 投放影片內容

插圖:搭載 CastVideos 應用程式的 iPhone,顯示特定影片的詳細資料 (《Tears of Steel」)。畫面底部是小型播放器

我們將擴充範例應用程式,以便在投放裝置上遠端播放影片。如要這麼做,我們必須監聽 Cast 架構產生的各種事件。

正在投放媒體

整體而言,如要在投放裝置上播放媒體,必須符合下列條件:

  1. 從 Cast SDK 建立 GCKMediaInformation 物件,用來建立媒體項目模型。
  2. 使用者連線至 Cast 裝置,啟動接收器應用程式。
  3. GCKMediaInformation 物件載入接收器,然後播放內容。
  4. 追蹤媒體狀態。
  5. 根據使用者互動,向接收器傳送播放指令。

步驟 1 的作用是將物件對應至另一個物件;GCKMediaInformation 是 Cast SDK 可解讀的內容,而 MediaItem 是應用程式的媒體項目的封裝。我們就能輕鬆將 MediaItem 對應至 GCKMediaInformation我們已在上一節完成步驟 2。步驟 3 可搭配 Cast SDK 使用。

範例應用程式 MediaViewController 已使用這個列舉方式區分本機與遠端播放作業:

enum PlaybackMode: Int {
  case none = 0
  case local
  case remote
}

private var playbackMode = PlaybackMode.none

在本程式碼研究室中,您不一定要瞭解所有範例播放器邏輯的運作方式。請務必瞭解,您的應用程式媒體播放器需要修改,才能以類似的方式掌握兩個播放位置。

目前本機播放器總是處於本機播放狀態,因為它尚不知道投放狀態的任何資訊。我們必須根據 Cast 架構中發生的狀態轉換來更新 UI。舉例來說,如果我們開始投放,就必須停止本機播放並停用部分控制項。同理,如果在進入這個檢視控制器時停止投放,我們就必須轉換成本機播放。為了處理這項錯誤,我們需要監聽 Cast 架構產生的各種事件。

投放工作階段管理

對於 Cast 架構而言,Cast 工作階段會結合連線至裝置、啟動 (或加入)、連線至接收器應用程式,以及在適當情況下初始化媒體控制管道的步驟。媒體控制管道是 Cast 架構收發接收器媒體播放器訊息的方式。

使用者從「投放」按鈕選取裝置後,「投放」工作階段就會自動開始,並在使用者中斷連線時自動停止。由於網路問題而重新連線至接收器工作階段,Cast 架構也會自動處理。

投放工作階段是由 GCKSessionManager 管理,可透過 GCKCastContext.sharedInstance().sessionManager 存取。GCKSessionManagerListener 回呼可用來監控工作階段事件,例如建立、暫停、恢復和終止。

首先,我們必須註冊工作階段事件監聽器,並初始化部分變數:

class MediaViewController: UIViewController, GCKSessionManagerListener,
  GCKRemoteMediaClientListener, LocalPlayerViewDelegate, GCKRequestDelegate {

  ...
  private var sessionManager: GCKSessionManager!
  ...

  required init?(coder: NSCoder) {
    super.init(coder: coder)

    sessionManager = GCKCastContext.sharedInstance().sessionManager

    ...
  }

  override func viewWillAppear(_ animated: Bool) {
    ...

    let hasConnectedSession: Bool = (sessionManager.hasConnectedSession())
    if hasConnectedSession, (playbackMode != .remote) {
      populateMediaInfo(false, playPosition: 0)
      switchToRemotePlayback()
    } else if sessionManager.currentSession == nil, (playbackMode != .local) {
      switchToLocalPlayback()
    }

    sessionManager.add(self)

    ...
  }

  override func viewWillDisappear(_ animated: Bool) {
    ...

    sessionManager.remove(self)
    sessionManager.currentCastSession?.remoteMediaClient?.remove(self)
    ...
    super.viewWillDisappear(animated)
  }

  func switchToLocalPlayback() {
    ...

    sessionManager.currentCastSession?.remoteMediaClient?.remove(self)

    ...
  }

  func switchToRemotePlayback() {
    ...

    sessionManager.currentCastSession?.remoteMediaClient?.add(self)

    ...
  }


  // MARK: - GCKSessionManagerListener

  func sessionManager(_: GCKSessionManager, didStart session: GCKSession) {
    print("MediaViewController: sessionManager didStartSession \(session)")
    setQueueButtonVisible(true)
    switchToRemotePlayback()
  }

  func sessionManager(_: GCKSessionManager, didResumeSession session: GCKSession) {
    print("MediaViewController: sessionManager didResumeSession \(session)")
    setQueueButtonVisible(true)
    switchToRemotePlayback()
  }

  func sessionManager(_: GCKSessionManager, didEnd _: GCKSession, withError error: Error?) {
    print("session ended with error: \(String(describing: error))")
    let message = "The Casting session has ended.\n\(String(describing: error))"
    if let window = appDelegate?.window {
      Toast.displayMessage(message, for: 3, in: window)
    }
    setQueueButtonVisible(false)
    switchToLocalPlayback()
  }

  func sessionManager(_: GCKSessionManager, didFailToStartSessionWithError error: Error?) {
    if let error = error {
      showAlert(withTitle: "Failed to start a session", message: error.localizedDescription)
    }
    setQueueButtonVisible(false)
  }

  func sessionManager(_: GCKSessionManager,
                      didFailToResumeSession _: GCKSession, withError _: Error?) {
    if let window = UIApplication.shared.delegate?.window {
      Toast.displayMessage("The Casting session could not be resumed.",
                           for: 3, in: window)
    }
    setQueueButtonVisible(false)
    switchToLocalPlayback()
  }

  ...
}

MediaViewController,我們希望在與投放裝置連線或中斷連線時收到相關通知,以便切換或退出本機播放器。請注意,在行動裝置上執行的應用程式執行個體,不僅可能會中斷連線,而且在另一部行動裝置上執行的另一個應用程式執行個體也可能會中斷連線。

目前使用中的工作階段可透過 GCKCastContext.sharedInstance().sessionManager.currentCastSession 存取。系統會根據投放對話方塊的使用者手勢,自動建立及關閉工作階段。

正在載入媒體

在 Cast SDK 中,GCKRemoteMediaClient 提供一組便利的 API,可用來管理接收器上的遠端媒體播放作業。針對支援媒體播放的 GCKCastSession,SDK 會自動建立 GCKRemoteMediaClient 的執行個體。它可以做為 GCKCastSession 執行個體的 remoteMediaClient 屬性存取。

將下列程式碼新增至 MediaViewController.swift,即可在接收端載入目前選取的影片:

@objc(MediaViewController)
class MediaViewController: UIViewController, GCKSessionManagerListener,
  GCKRemoteMediaClientListener, LocalPlayerViewDelegate, GCKRequestDelegate {
  ...

  @objc func playSelectedItemRemotely() {
    loadSelectedItem(byAppending: false)
  }

  /**
   * Loads the currently selected item in the current cast media session.
   * @param appending If YES, the item is appended to the current queue if there
   * is one. If NO, or if
   * there is no queue, a new queue containing only the selected item is created.
   */
  func loadSelectedItem(byAppending appending: Bool) {
    print("enqueue item \(String(describing: mediaInfo))")
    if let remoteMediaClient = sessionManager.currentCastSession?.remoteMediaClient {
      let mediaQueueItemBuilder = GCKMediaQueueItemBuilder()
      mediaQueueItemBuilder.mediaInformation = mediaInfo
      mediaQueueItemBuilder.autoplay = true
      mediaQueueItemBuilder.preloadTime = TimeInterval(UserDefaults.standard.integer(forKey: kPrefPreloadTime))
      let mediaQueueItem = mediaQueueItemBuilder.build()
      if appending {
        let request = remoteMediaClient.queueInsert(mediaQueueItem, beforeItemWithID: kGCKMediaQueueInvalidItemID)
        request.delegate = self
      } else {
        let queueDataBuilder = GCKMediaQueueDataBuilder(queueType: .generic)
        queueDataBuilder.items = [mediaQueueItem]
        queueDataBuilder.repeatMode = remoteMediaClient.mediaStatus?.queueRepeatMode ?? .off

        let mediaLoadRequestDataBuilder = GCKMediaLoadRequestDataBuilder()
        mediaLoadRequestDataBuilder.mediaInformation = mediaInfo
        mediaLoadRequestDataBuilder.queueData = queueDataBuilder.build()

        let request = remoteMediaClient.loadMedia(with: mediaLoadRequestDataBuilder.build())
        request.delegate = self
      }
    }
  }
  ...
}

現在更新各種現有方法,使用 Cast 工作階段邏輯以支援遠端播放:

required init?(coder: NSCoder) {
  super.init(coder: coder)
  ...
  castMediaController = GCKUIMediaController()
  ...
}

func switchToLocalPlayback() {
  print("switchToLocalPlayback")
  if playbackMode == .local {
    return
  }
  setQueueButtonVisible(false)
  var playPosition: TimeInterval = 0
  var paused: Bool = false
  var ended: Bool = false
  if playbackMode == .remote {
    playPosition = castMediaController.lastKnownStreamPosition
    paused = (castMediaController.lastKnownPlayerState == .paused)
    ended = (castMediaController.lastKnownPlayerState == .idle)
    print("last player state: \(castMediaController.lastKnownPlayerState), ended: \(ended)")
  }
  populateMediaInfo((!paused && !ended), playPosition: playPosition)
  sessionManager.currentCastSession?.remoteMediaClient?.remove(self)
  playbackMode = .local
}

func switchToRemotePlayback() {
  print("switchToRemotePlayback; mediaInfo is \(String(describing: mediaInfo))")
  if playbackMode == .remote {
    return
  }
  // If we were playing locally, load the local media on the remote player
  if playbackMode == .local, (_localPlayerView.playerState != .stopped), (mediaInfo != nil) {
    print("loading media: \(String(describing: mediaInfo))")
    let paused: Bool = (_localPlayerView.playerState == .paused)
    let mediaQueueItemBuilder = GCKMediaQueueItemBuilder()
    mediaQueueItemBuilder.mediaInformation = mediaInfo
    mediaQueueItemBuilder.autoplay = !paused
    mediaQueueItemBuilder.preloadTime = TimeInterval(UserDefaults.standard.integer(forKey: kPrefPreloadTime))
    mediaQueueItemBuilder.startTime = _localPlayerView.streamPosition ?? 0
    let mediaQueueItem = mediaQueueItemBuilder.build()

    let queueDataBuilder = GCKMediaQueueDataBuilder(queueType: .generic)
    queueDataBuilder.items = [mediaQueueItem]
    queueDataBuilder.repeatMode = .off

    let mediaLoadRequestDataBuilder = GCKMediaLoadRequestDataBuilder()
    mediaLoadRequestDataBuilder.queueData = queueDataBuilder.build()

    let request = sessionManager.currentCastSession?.remoteMediaClient?.loadMedia(with: mediaLoadRequestDataBuilder.build())
    request?.delegate = self
  }
  _localPlayerView.stop()
  _localPlayerView.showSplashScreen()
  setQueueButtonVisible(true)
  sessionManager.currentCastSession?.remoteMediaClient?.add(self)
  playbackMode = .remote
}

/* Play has been pressed in the LocalPlayerView. */
func continueAfterPlayButtonClicked() -> Bool {
  let hasConnectedCastSession = sessionManager.hasConnectedCastSession
  if mediaInfo != nil, hasConnectedCastSession() {
    // Display an alert box to allow the user to add to queue or play
    // immediately.
    if actionSheet == nil {
      actionSheet = ActionSheet(title: "Play Item", message: "Select an action", cancelButtonText: "Cancel")
      actionSheet?.addAction(withTitle: "Play Now", target: self,
                             selector: #selector(playSelectedItemRemotely))
    }
    actionSheet?.present(in: self, sourceView: _localPlayerView)
    return false
  }
  return true
}

現在,在行動裝置上執行應用程式。連線至投放裝置,然後開始播放影片。您應該會看到接收器正在播放視訊畫面。

7. 迷你控制器

根據「投放設計檢查清單」規定,所有投放應用程式均提供迷你控制器,當使用者離開目前內容頁面時,應用程式才會顯示。迷你控制器可讓你即時存取目前的投放工作階段,並顯示一則顯示提醒。

插圖:執行 CastVideos 應用程式的 iPhone 底部部分,並聚焦在迷你控制器

Cast SDK 提供控制列 GCKUIMiniMediaControlsViewController,您可以將這個控制列加到要顯示永久控制項的場景中。

在範例應用程式中,我們會使用 GCKUICastContainerViewController,包裝另一個檢視控制器,並在底部新增 GCKUIMiniMediaControlsViewController

修改 AppDelegate.swift 檔案,並透過以下方法為 if useCastContainerViewController 條件新增下列程式碼:

func application(_: UIApplication,
                 didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  ...
  let appStoryboard = UIStoryboard(name: "Main", bundle: nil)
  guard let navigationController = appStoryboard.instantiateViewController(withIdentifier: "MainNavigation")
    as? UINavigationController else { return false }
  let castContainerVC = GCKCastContext.sharedInstance().createCastContainerController(for: navigationController)
    as GCKUICastContainerViewController
  castContainerVC.miniMediaControlsItemEnabled = true
  window = UIWindow(frame: UIScreen.main.bounds)
  window?.rootViewController = castContainerVC
  window?.makeKeyAndVisible()
  ...
}

新增這個屬性和 setter/getter 來控制迷你控制器的顯示設定 (我們會在後續章節中用到這些項目):

var isCastControlBarsEnabled: Bool {
    get {
      if useCastContainerViewController {
        let castContainerVC = (window?.rootViewController as? GCKUICastContainerViewController)
        return castContainerVC!.miniMediaControlsItemEnabled
      } else {
        let rootContainerVC = (window?.rootViewController as? RootContainerViewController)
        return rootContainerVC!.miniMediaControlsViewEnabled
      }
    }
    set(notificationsEnabled) {
      if useCastContainerViewController {
        var castContainerVC: GCKUICastContainerViewController?
        castContainerVC = (window?.rootViewController as? GCKUICastContainerViewController)
        castContainerVC?.miniMediaControlsItemEnabled = notificationsEnabled
      } else {
        var rootContainerVC: RootContainerViewController?
        rootContainerVC = (window?.rootViewController as? RootContainerViewController)
        rootContainerVC?.miniMediaControlsViewEnabled = notificationsEnabled
      }
    }
  }

執行應用程式並投放影片。接收器開始播放時,每個場景的底部應該都會顯示迷你控制器。您可以使用迷你控制器控制遠端播放內容。如果您在瀏覽活動和本機播放器活動之間進行瀏覽,迷你控制器狀態應與接收器媒體播放狀態保持同步。

8. 簡介重疊

Google Cast 設計檢查清單要求發送者應用程式為現有的使用者介紹「投放」按鈕,讓對方瞭解傳送端應用程式現在可支援投放功能,並協助剛開始使用 Google Cast 的使用者。

插圖:iPhone 執行 CastVideos 應用程式,顯示投放按鈕疊加層,並以醒目顯示投放按鈕,以及顯示「Touch to cast media to your TV and Speakers」訊息

GCKCastContext 類別包含 presentCastInstructionsViewControllerOnce 方法,可用於在使用者首次向使用者顯示「投放」按鈕時醒目顯示。將以下程式碼加入 MediaViewController.swiftMediaTableViewController.swift

override func viewDidLoad() {
  ...

  NotificationCenter.default.addObserver(self, selector: #selector(castDeviceDidChange),
                                         name: NSNotification.Name.gckCastStateDidChange,
                                         object: GCKCastContext.sharedInstance())
}

@objc func castDeviceDidChange(_: Notification) {
  if GCKCastContext.sharedInstance().castState != .noDevicesAvailable {
    // You can present the instructions on how to use Google Cast on
    // the first time the user uses you app
    GCKCastContext.sharedInstance().presentCastInstructionsViewControllerOnce(with: castButton)
  }
}

在行動裝置上執行應用程式後,應該會看到簡介重疊畫面。

9. 展開的控制器

Google Cast 設計檢查清單要求傳送者應用程式為要投放的媒體提供展開控制器。展開的控制器是全螢幕的迷你控制器的全螢幕版本。

插圖:搭載 CastVideos 應用程式的 iPhone 播放影片,底部有一個展開的控制器顯示在影片底部

展開的控制器是一種全螢幕檢視,可讓您完全控制遠端媒體播放。這個檢視畫面應可讓投放應用程式管理投放工作階段的每個可管理層面,但接收端音量控制和工作階段生命週期 (連線/停止投放) 除外。並提供媒體工作階段的所有狀態資訊 (圖片、標題、副標題等)。

此檢視畫面的功能是由 GCKUIExpandedMediaControlsViewController 類別實作。

首先,您必須在投放環境中啟用預設的展開控制器。修改 AppDelegate.swift,啟用預設展開控制器:

import GoogleCast

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  ...

  func application(_: UIApplication,
                   didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    ...
    // Add after the setShareInstanceWith(options) is set.
    GCKCastContext.sharedInstance().useDefaultExpandedMediaControls = true
    ...
  }
  ...
}

將下列程式碼新增至 MediaViewController.swift,在使用者開始投放影片時載入展開的控制器:

@objc func playSelectedItemRemotely() {
  ...
  appDelegate?.isCastControlBarsEnabled = false
  GCKCastContext.sharedInstance().presentDefaultExpandedMediaControls()
}

使用者輕觸迷你控制器時,也會自動啟動展開的控制器。

執行應用程式並投放影片。您應該會看到展開的控制器。回到影片清單,當您按一下迷你控制器時,會再次載入展開的控制器。

10. 新增 Cast Connect 支援

Cast Connect 程式庫可讓現有的傳送端應用程式透過 Cast 通訊協定與 Android TV 應用程式通訊。Cast Connect 是以 Cast 基���������為基礎,而 Android TV 應用程式則充當接收端。

依附元件

Podfile 中,確認 google-cast-sdk 指向 4.4.8 以上,如下所列。如果您修改了檔案,請從控制台執行 pod update,將變更內容與專案同步。

pod 'google-cast-sdk', '>=4.4.8'

GCKLaunchOptions

為了啟動 Android TV 應用程式 (也稱為 Android 接收器),我們必須將 GCKLaunchOptions 物件的 androidReceiverCompatible 標記設為 true。這個 GCKLaunchOptions 物件會指定接收器的啟動方式,並傳遞至使用 GCKCastContext.setSharedInstanceWith 在共用執行個體中設定的 GCKCastOptions

AppDelegate.swift 中新增下列程式碼行:

let options = GCKCastOptions(discoveryCriteria:
                          GCKDiscoveryCriteria(applicationID: kReceiverAppID))
...
/** Following code enables CastConnect */
let launchOptions = GCKLaunchOptions()
launchOptions.androidReceiverCompatible = true
options.launchOptions = launchOptions

GCKCastContext.setSharedInstanceWith(options)

設定啟動憑證

在傳送者端,您可以指定 GCKCredentialsData 來代表加入工作階段的使用者。credentials 是可以由使用者定義的字串,前提是您的 ATV 應用程式可以理解。只有在啟動或加入期間,GCKCredentialsData 才會傳遞至您的 Android TV 應用程式。如果在連線後再次設定 PIN 碼,就不會傳送到 Android TV 應用程式。

如要設定啟動憑證,GCKCredentialsData 必須在 GCKLaunchOptions 設定後的任何時間定義。為說明這項功能,我們將為「Creds」按鈕新增邏輯,在建立工作階段時設定要傳遞的憑證。將下列程式碼新增至您的 MediaTableViewController.swift

class MediaTableViewController: UITableViewController, GCKSessionManagerListener, MediaListModelDelegate, GCKRequestDelegate {
  ...
  private var credentials: String? = nil
  ...
  override func viewDidLoad() {
    ...
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Creds", style: .plain,
                                                       target: self, action: #selector(toggleLaunchCreds))
    ...
    setLaunchCreds()
  }
  ...
  @objc func toggleLaunchCreds(_: Any){
    if (credentials == nil) {
        credentials = "{\"userId\":\"id123\"}"
    } else {
        credentials = nil
    }
    Toast.displayMessage("Launch Credentials: "+(credentials ?? "Null"), for: 3, in: appDelegate?.window)
    print("Credentials set: "+(credentials ?? "Null"))
    setLaunchCreds()
  }
  ...
  func setLaunchCreds() {
    GCKCastContext.sharedInstance()
        .setLaunch(GCKCredentialsData(credentials: credentials))
  }
}

設定載入要求的憑證

如要在網頁和 Android TV 接收器應用程式中處理 credentials,請在 MediaTableViewController.swift 類別的 loadSelectedItem 函式下方加入下列程式碼:

let mediaLoadRequestDataBuilder = GCKMediaLoadRequestDataBuilder()
...
mediaLoadRequestDataBuilder.credentials = credentials
...

視傳送端投放至哪個接收端應用程式而定,SDK 會自動將上述憑證套用到進行中的工作階段。

測試 Cast Connect

在 Chromecast (支援 Google TV) 上安裝 Android TV APK 的步驟

  1. 找出 Android TV 裝置的 IP 位址。通常位於 [設定] > []網路和網際網路 >(裝置連線的網路名稱)。畫面右側會顯示詳細資料和裝置的 IP。
  2. 使用裝置的 IP 位址,以便透過終端機透過 ADB 連線:
$ adb connect <device_ip_address>:5555
  1. 在終端機視窗中,前往您在本程式碼研究室一開始下載的程式碼研究室範例的頂層資料夾。例如:
$ cd Desktop/ios_codelab_src
  1. 請執行下列指令,將此資料夾中的 .apk 檔案安裝至 Android TV:
$ adb -s <device_ip_address>:5555 install android-tv-app.apk
  1. 現在,您應該會在 Android TV 裝置上,透過「您的應用程式」選單的「投放影片」名稱看到應用程式。
  2. 完成後,請在模擬器或行動裝置上建構並執行應用程式。使用 Android TV 裝置建立投放工作階段時,系統應會在 Android TV 上啟動 Android 接收器應用程式。播放 iOS 行動裝置傳送來源的影片後,您應該會透過 Android 接收器播放影片,並且讓您使用 Android TV 裝置的遙控器控製播放。

11. 自訂 Cast 小工具

初始化

請先從「App-Done」資料夾開始。請在 AppDelegate.swift 檔案的 applicationDidFinishLaunchingWithOptions 方法中新增以下內容。

func application(_: UIApplication,
                 didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  ...
  let styler = GCKUIStyle.sharedInstance()
  ...
}

按照本程式碼研究室其他章節所述,套用一或多個自訂項目後,請呼叫以下程式碼提交這些樣式

styler.apply()

自訂投放檢視畫面

如要自訂 Cast 應用程式架構管理的所有檢視畫面,請針對各個檢視畫面使用預設樣式規範。例如,變更圖示的色調顏色。

styler.castViews.iconTintColor = .lightGray

如有需要,您可以覆寫個別畫面的預設值。例如,只針對展開的媒體控制器,覆寫圖示色調顏色的 lightGrayColor。

styler.castViews.mediaControl.expandedController.iconTintColor = .green

變更色彩

您可以自訂所有檢視畫面的背景顏色,或個別自訂每個檢視畫面的背景顏色。下方程式碼會將所有 Cast 應用程式架構提供的檢視畫面背景顏色設為藍色。

styler.castViews.backgroundColor = .blue
styler.castViews.mediaControl.miniController.backgroundColor = .yellow

變更字型

您可以為投放檢視畫面中顯示的各種標籤自訂字型。將所有字型設為「Courier-Oblique」說明。

styler.castViews.headingTextFont = UIFont.init(name: "Courier-Oblique", size: 16) ?? UIFont.systemFont(ofSize: 16)
styler.castViews.mediaControl.headingTextFont = UIFont.init(name: "Courier-Oblique", size: 6) ?? UIFont.systemFont(ofSize: 6)

變更預設按鈕圖片

在專案中加入自訂圖片,並指定按鈕至按鈕,即可設定圖片樣式。

let muteOnImage = UIImage.init(named: "yourImage.png")
if let muteOnImage = muteOnImage {
  styler.castViews.muteOnImage = muteOnImage
}

變更「投放」按鈕的主題

你也可以使用 UIAppearance 通訊協定,為 Cast 小工具設定主題。下列程式碼是 GCKUICastButton 顯示在所有檢視畫面上的主題:

GCKUICastButton.appearance().tintColor = UIColor.gray

12. 恭喜

您已瞭解如何為 iOS 裝置上的 Cast SDK 小工具啟用投放功能。

詳情請參閱 iOS 寄件者開發人員指南。