使用 YouTube 小幫手程式庫,在 iOS 應用程式中嵌入 YouTube 影片
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
youtube-ios-player-helper
是一個開放原始碼程式庫,可協助您將 YouTube iframe 播放器嵌入 iOS 應用程式中。這個程式庫會在應用程式的 Objective-C 程式碼與 YouTube 播放器的 JavaScript 程式碼之間建立 WebView
及橋接設定,讓 iOS 應用程式能夠控制 YouTube 播放器。本文說明如何安裝程式庫,並透過 iOS 應用程式開始使用這個程式庫。
安裝
本文假設您建立了新的 iOS 應用程式,並指定 iOS 最新版本,並在建立專案時新增下列檔案:
Main.storyboard
ViewController.h
ViewController.m
您可以透過 CocoaPods 安裝程式庫,或是從專案的 GitHub 頁面複製程式庫和來源檔案。
- 此程式庫可透過 CocoaPods 安裝。或者,您可以透過專案的 GitHub 頁面取得程式庫和來源檔案,也可以複製到現有專案。
透過 CocoaPods 安裝程式庫
如果您的專案使用 CocoaPods,請在 Podfile 中加入以下這一行,以安裝程式庫。
在該行中,將 x.y.z
替換為最新 Pod 版本,該版本將在專案的 GitHub 頁面上進行識別。
pod "youtube-ios-player-helper", "~> x.y.z"
在指令列提示中輸入 pod install
,以將依附元件更新為工作區。
提示:請注意,使用 CocoaPods 時,您必須在 Xcode 中開啟 .xcworkspace
檔案,而不是 .xcodeproj
檔案。
詳情請參閱 CocoaPods 教學課程。
手動安裝程式庫
如要手動安裝輔助程式庫,請透過 GitHub 的下載連結下載原始碼,或複製存放區。取得本機的本機副本後,請按照下列步驟操作:
在 Xcode 或 Finder 中開啟範例專案。
選取 YTPlayerView.h
、YTPlayerView.m
和 Assets 資料夾。如果您在 Xcode 中開啟工作區,就可以在 Pods -> Development Pod -> YouTube-Player-iOS-Helper 和 Pods -> Development Pod -> YouTube-Player-iOS-Helper -> Resources 下找到工作區。您可以在 Finder 的 Class 和 Assets 目錄中的專案根目錄中找到這些項目。
將這些檔案和資料夾拖曳到專案中。確認已勾選 [Copy items to destination group's folder] 選項。拖曳「Assets」資料夾時,請務必勾選 [Create a FolderReferences for any added folders] (為所有新增的資料夾建立資料夾參照) 選項。
系統現在應已安裝程式庫。
透過介面建構工具或分鏡腳本新增 YTPlayerView
如何透過介面建構工具或分鏡腳本新增 YTPlayerView
:
-
將 UIView
執行個體拖曳至您的 View 中。
-
選取身分檢查器,並將檢視區塊類別變更為 YTPlayerView
。
-
開啟 ViewController.h
並新增下列標頭:
#import “YTPlayerView.h”
請一併加入下列屬性:
@property(nonatomic, strong) IBOutlet YTPlayerView *playerView;
-
在介面製作工具中,從您在上一步定義的 View 元素建立連線,並連結至 View Controller 的 playerView
屬性。
-
現在,請開啟 ViewController.m
,並將下列程式碼加進 viewDidLoad
方法的結尾:
[self.playerView loadWithVideoId:@"M7lc1UVf-VE"];
Build and run your application. 影片縮圖載入後,輕觸影片縮圖即可啟動全螢幕影片播放器。
控制影片播放
ViewController::loadWithVideoId:
方法有 loadWithVideoId:playerVars:
變數,可讓開發人員將其他玩家變數傳遞至檢視區塊。這些播放器變數會對應到 IFrame Player API 中的播放器參數。playsinline
參數可讓影片直接在檢視畫面中播放,而不是以全螢幕模式播放。以內嵌方式播放影片時,包含 iOS 應用程式的程式可透過程式輔助方式控製播放方式。
使用下列程式碼取代 loadWithVideoId:
呼叫:
NSDictionary *playerVars = @{
@"playsinline" : @1,
};
[self.playerView loadWithVideoId:@"M7lc1UVf-VE" playerVars:playerVars];
開啟分鏡腳本或介面建立工具。將兩個按鈕拖曳至您的檢視畫面上,並為「播放」和「停止」標籤加上標籤。開啟 ViewController.h
並新增以下方法,這些方法將對應至按鈕:
- (IBAction)playVideo:(id)sender;
- (IBAction)stopVideo:(id)sender;
現在,請開啟 ViewController.m
並定義以下兩個函式:
- (IBAction)playVideo:(id)sender {
[self.playerView playVideo];
}
- (IBAction)stopVideo:(id)sender {
[self.playerView stopVideo];
}
大部分的 IFrame Player API 函式都有 Objective-C 對等項目,但部分命名方式可能略有不同,以便更符合 Objective-C 編碼規範。值得注意的例外狀況是控制影片音量的方法,因為這些方法是由手機硬體或內建用於此用途的 UIView
執行個體所控制,例如 MPVolumeView
。
開啟分鏡腳本或介面建構工具,並按住 拖曳 即可將「播放」和「停止」按鈕連結到 playVideo:
和 stopVideo:
方法。
現在,請建構並執行應用程式。影片縮圖載入後,除了播放器控制項之外,您還能使用原生控制項播放及停止播放影片。
處理玩家回呼
您可以利用程式處理播放事件,例如播放狀態變更和播放錯誤。在 JavaScript API 中,這會透過事件監聽器來完成。在目標 C 中,可透過委派來完成。
以下程式碼示範如何更新 ViewController.h
中的介面宣告,以便該類別符合委派通訊協定。按照下列方式變更 ViewController.h
的介面宣告:
@interface ViewController : UIViewController<YTPlayerViewDelegate>
YTPlayerViewDelegate
是用於處理播放器中的播放事件的通訊協定。
如要更新 ViewController.m
來處理部分事件,您必須先將 ViewController
執行個體設為 YTPlayerView
執行個體的委派項目。如要進行這項變更,請在 ViewController.h
的 viewDidLoad
方法中加入以下這一行。
self.playerView.delegate = self;
現在,將下列方法新增至 ViewController.m
:
- (void)playerView:(YTPlayerView *)playerView didChangeToState:(YTPlayerState)state {
switch (state) {
case kYTPlayerStatePlaying:
NSLog(@"Started playback");
break;
case kYTPlayerStatePaused:
NSLog(@"Paused playback");
break;
default:
break;
}
}
建構並執行應用程式。隨著播放器狀態改變,請檢視 Xcode 中的記錄輸出。當影片播放或停止時,畫面上應會顯示更新。
程式庫提供以 kYT*
前置字串開頭的常數,以方便閱讀。如需這些常數的完整清單,請參閱 YTPlayerView.m
。
最佳做法和限制
這個程式庫以 IFrame Player API 為基礎而建構,藉此建立 WebView
並轉譯基本播放器所需的 HTML 和 JavaScript。這個程式庫的目標,是讓開發人員能夠輕鬆寫入套件。需要注意的幾個限制如下:
- 程式庫不支援在多個
YTPlayerView
執行個體同時播放影片。如果您的應用程式有多個 YTPlayerView
執行個體,建議的最佳做法是先暫停或停止任何現有執行個體中的播放作業,然後再在其他執行個體中開始播放。在專案隨附的應用程式應用程式中,ViewController 會使用 NSNotificationCenter
來分派播放即將開始的通知。其他 ViewController 會收到通知,且會在其 YTPlayerView
執行個體中暫停播放。
- 盡可能重複使用已載入的現有
YTPlayerView
執行個體。如果需要變更檢視畫面中的影片,請勿建立新的 UIView
執行個體或新的 YTPlayerView
執行個體,且不要呼叫 loadVideoId:
或 loadPlaylistId:
。請改用 cueVideoById:startSeconds:
系列函式,該函式並不會重新載入 WebView
。載入整個 iFrame 播放器時,可能會出現明顯延遲。
- 這位玩家無法播放私人影片,但可以播放不公開的影片。由於這個程式庫會納入現有的 iframe 播放器,因此播放器的行為應與在行動瀏覽器中內嵌的播放器行為幾乎相同。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2023-02-22 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2023-02-22 (世界標準時間)。"],[[["\u003cp\u003eThis library, \u003ccode\u003eyoutube-ios-player-helper\u003c/code\u003e, facilitates embedding a YouTube iframe player within an iOS application by creating a \u003ccode\u003eWebView\u003c/code\u003e and bridging Objective-C code with the player's JavaScript.\u003c/p\u003e\n"],["\u003cp\u003eInstallation is possible via CocoaPods by adding a specific line to the Podfile, or manually by downloading the source code from the project's GitHub page and dragging specific files into your iOS project.\u003c/p\u003e\n"],["\u003cp\u003eA \u003ccode\u003eYTPlayerView\u003c/code\u003e can be added through Interface Builder or Storyboard by dragging a \u003ccode\u003eUIView\u003c/code\u003e, changing its class to \u003ccode\u003eYTPlayerView\u003c/code\u003e, and connecting it to a \u003ccode\u003eplayerView\u003c/code\u003e property in the \u003ccode\u003eViewController.h\u003c/code\u003e file.\u003c/p\u003e\n"],["\u003cp\u003eThe library allows for controlling video playback, enabling inline play and manipulation using the IFrame Player API through Objective-C equivalent methods.\u003c/p\u003e\n"],["\u003cp\u003eThe library allows the handling of playback events, such as start and stop, through a delegate protocol, \u003ccode\u003eYTPlayerViewDelegate\u003c/code\u003e, where the \u003ccode\u003eViewController\u003c/code\u003e conforms to this protocol to capture those events.\u003c/p\u003e\n"]]],["The `youtube-ios-player-helper` library enables embedding and controlling a YouTube iframe player within an iOS app. Installation is via CocoaPods or manual file copying from GitHub. To use, a `YTPlayerView` is added to the storyboard, connected to a `ViewController`, and initialized with a video ID. Playback is controlled through Objective-C methods (e.g., `playVideo`, `stopVideo`) linked to UI elements. Developers can pass player variables, and the library supports delegate-based event handling for playback states. The library is based on the iFrame Player API and includes a few limitations.\n"],null,["# Embed YouTube Videos in iOS Applications with the YouTube Helper Library\n\nThe `youtube-ios-player-helper` is an open source library that helps you embed a\nYouTube iframe player into an iOS application. The library creates a\n`WebView` and a bridge between your application's Objective-C code and the\nYouTube player's JavaScript code, thereby allowing the iOS application to control the\nYouTube player. This article describes the steps to install the library and get started\nusing it from your iOS application.\n\nInstallation\n------------\n\nThis article assumes you have created a new Single View Application iOS project targeting\nthe latest version of iOS, and that you add the following files when creating the\nproject:\n\n- `Main.storyboard`\n- `ViewController.h`\n- `ViewController.m`\n\nYou can install the library via\n[CocoaPods](https://cocoapods.org/) or by copying the library\nand source files from the\n[project's GitHub page](https://github.com/youtube/youtube-ios-player-helper).\n\n- The library is available to install via CocoaPods. Alternatively, the library and source files are available via the project's GitHub page and can be copied into an existing project.\n\n### Install the library via CocoaPods\n\nIf your project uses CocoaPods, add the line below to your Podfile to install the library.\nIn that line, replace `x.y.z` with the latest pod version, which will be\nidentified on the project's GitHub page. \n\n```text\npod \"youtube-ios-player-helper\", \"~\u003e x.y.z\"\n```\n\nAt the command line prompt, type `pod install` to update your workspace with the\ndependencies.\n\nTip: Remember that when using CocoaPods, you must open the `.xcworkspace` file\nin Xcode, not the `.xcodeproj` file.\n\nCheck out the [CocoaPods\ntutorial](https://guides.cocoapods.org/using/getting-started.html) to learn more.\n\n### Manually install the library\n\nTo install the helper library manually, either download the source via\n[GitHub's download link](https://github.com/youtube/youtube-ios-player-helper) or\nclone the repository. Once you have a local copy of the code, follow these steps:\n\n1. Open the sample project in Xcode or Finder.\n\n2. Select `YTPlayerView.h`, `YTPlayerView.m`, and the\n **Assets** folder. If you open the workspace in Xcode, these are available\n under **Pods -\\\u003e Development Pods -\\\u003e YouTube-Player-iOS-Helper** and\n **Pods -\\\u003e Development Pods -\\\u003e YouTube-Player-iOS-Helper -\\\u003e Resources** . In the Finder,\n these are available in the project's root directory in the **Classes** and\n **Assets** directories.\n\n3. Drag these files and folders into your project. Make sure the **Copy items into\n destination group's folder** option is checked. When dragging the Assets folder, make\n sure that the **Create Folder References for any added folders** option is\n checked.\n\nThe library should now be installed.\n\nAdd a `YTPlayerView` via Interface Builder or the Storyboard\n------------------------------------------------------------\n\nTo add a `YTPlayerView` via Interface Builder or the Storyboard:\n\n1. Drag a `UIView` instance onto your View.\n\n2. Select the Identity Inspector and change the class of the view to\n `YTPlayerView`.\n\n3. Open `ViewController.h` and add the following header:\n\n ```objective-c\n #import \"YTPlayerView.h\"\n ```\n\n Also add the following property: \n\n ```objective-c\n @property(nonatomic, strong) IBOutlet YTPlayerView *playerView;\n ```\n4. In Interface Builder, create a connection from the View element that you defined in the\n previous step to your View Controller's `playerView` property.\n\n5. Now open `ViewController.m` and add the following code to the end of your\n `viewDidLoad` method:\n\n ```objective-c\n [self.playerView loadWithVideoId:@\"M7lc1UVf-VE\"];\n ```\n\nBuild and run your application. When the video thumbnail loads, tap the video thumbnail to\nlaunch the fullscreen video player.\n\nControl video playback\n----------------------\n\nThe `ViewController::loadWithVideoId:` method has a variant,\n`loadWithVideoId:playerVars:`, that allows developers to pass additional player\nvariables to the view. These player variables correspond to the\n[player parameters in the\nIFrame Player API](https://developers.google.com/youtube/player_parameters). The `playsinline` parameter enables the video to play\ndirectly in the view rather than playing fullscreen. When a video is playing inline, the\ncontaining iOS application can programmatically control playback.\n\nReplace the `loadWithVideoId:` call with this code: \n\n```objective-c\nNSDictionary *playerVars = @{\n @\"playsinline\" : @1,\n};\n[self.playerView loadWithVideoId:@\"M7lc1UVf-VE\" playerVars:playerVars];\n```\n\nOpen up the storyboard or Interface Builder. Drag two buttons onto your View, labeling them\n**Play** and **Stop** . Open `ViewController.h` and add these methods, which\nwill be mapped to the buttons: \n\n```objective-c\n- (IBAction)playVideo:(id)sender;\n- (IBAction)stopVideo:(id)sender;\n```\n\nNow open `ViewController.m` and define these two functions: \n\n```objective-c\n- (IBAction)playVideo:(id)sender {\n [self.playerView playVideo];\n}\n\n- (IBAction)stopVideo:(id)sender {\n [self.playerView stopVideo];\n}\n```\n\nMost of the IFrame Player API functions have Objective-C equivalents, though some of the\nnaming may differ slightly to more closely match Objective-C coding guidelines. Notable\nexceptions are methods controlling the volume of the video, since these are controlled by\nthe phone hardware or with built in `UIView` instances designed for this purpose,\nsuch as [`MPVolumeView`](https://developer.apple.com/library/ios/documentation/mediaplayer/reference/MPVolumeView_Class/Reference/Reference.html).\n\nOpen your storyboard or Interface Builder and control-drag to connect the **Play** and\n**Stop** buttons to the `playVideo:` and `stopVideo:` methods.\n\nNow build and run the application. Once the video thumbnail loads, you should be able to\nplay and stop the video using native controls in addition to the player controls.\n\nHandle player callbacks\n-----------------------\n\nIt can be useful to programmatically handle playback events, such as playback state changes\nand playback errors. In the JavaScript API, this is done with\n[event listeners](https://developers.google.com/youtube/iframe_api_reference#Adding_event_listener).\nIn Objective-C,this is done with a\n[delegate](https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/DelegatesandDataSources/DelegatesandDataSources.html).\n\n\nThe following code shows how to update the interface declaration in\n`ViewController.h` so the class conforms to the delegate protocol. Change\n`ViewController.h`'s interface declaration as follows: \n\n```objective-c\n@interface ViewController : UIViewController\u003cYTPlayerViewDelegate\u003e\n```\n\n`YTPlayerViewDelegate` is a protocol for handling playback events in the player.\nTo update `ViewController.m` to handle some of the events, you first need to set\nthe `ViewController` instance as the delegate of the `YTPlayerView`\ninstance. To make this change, add the following line to the `viewDidLoad` method\nin `ViewController.h`. \n\n```objective-c\nself.playerView.delegate = self;\n```\n\nNow add the following method to `ViewController.m`: \n\n```objective-c\n- (void)playerView:(YTPlayerView *)playerView didChangeToState:(YTPlayerState)state {\n switch (state) {\n case kYTPlayerStatePlaying:\n NSLog(@\"Started playback\");\n break;\n case kYTPlayerStatePaused:\n NSLog(@\"Paused playback\");\n break;\n default:\n break;\n }\n}\n```\n\nBuild and run the application. Watch the log output in Xcode as the player state changes.\nYou should see updates when the video is played or stopped.\n\nThe library provides the constants that begin with the `kYT*` prefix for\nconvenience and readability. For a full list of these constants, look at\n`YTPlayerView.m`.\n\nBest practices and limitations\n------------------------------\n\nThe library builds on top of the IFrame Player API by creating a `WebView` and\nrendering the HTML and JavaScript required for a basic player. The library's goal is to be\nas easy-to-use as possible, bundling methods that developers frequently have to write into a\npackage. There are a few limitations that should be noted:\n\n- The library does not support concurrent video playback in multiple `YTPlayerView` instances. If your application has multiple `YTPlayerView` instances, a recommended best practice is to pause or stop playback in any existing instances before starting playback in a different instance. In the example application that ships with the project, the ViewControllers make use of `NSNotificationCenter` to dispatch notifications that playback is about to begin. Other ViewControllers are notified and will pause playback in their `YTPlayerView` instances.\n- Reuse your existing, loaded `YTPlayerView` instances when possible. When a video needs to be changed in a View, don't create a new `UIView` instance or a new `YTPlayerView` instance, and don't call either `loadVideoId:` or `loadPlaylistId:`. Instead, use the `cueVideoById:startSeconds:` family of functions, which do not reload the `WebView`. There is a noticeable delay when loading the entire IFrame player.\n- This player cannot play private videos, but it can play [unlisted videos](https://support.google.com/youtube/answer/157177). Since this library wraps the existing iframe player, the player's behavior should be nearly identical to that of a player embedded on a webpage in a mobile browser.\n\nContributions\n-------------\n\nSince this is an open-source project, please submit fixes and improvements to the\n[master branch of the GitHub\nproject](https://github.com/youtube/youtube-ios-player-helper)."]]