YouTube ヘルパー ライブラリを使用して iOS アプリに YouTube 動画を埋め込む
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
youtube-ios-player-helper
は、YouTube iframe プレーヤーを iOS アプリに埋め込むためのオープンソース ライブラリです。このライブラリは、WebView
とアプリの Objective-C コードと YouTube プレーヤーの JavaScript コードの間のブリッジを作成します。これにより、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 を使用する場合は、.xcodeproj
ファイルではなく、Xcode で .xcworkspace
ファイルを開く必要があります。
詳しくは、CocoaPods チュートリアルをご覧ください。
ライブラリを手動でインストールする
ヘルパー ライブラリを手動でインストールするには、GitHub のダウンロード リンクを介してソースをダウンロードするか、リポジトリのクローンを作成します。コードのローカルコピーを入手したら、次の手順を行います。
Xcode または Finder でサンプル プロジェクトを開きます。
YTPlayerView.h
、YTPlayerView.m
、Assets フォルダを選択します。Xcode でワークスペースを開くと、[Pod] -> [Developd Pod] -> [YouTube-Player-iOS-Helper] および [Pods] -> [Development Pod] -> [YouTube-Player-iOS-Helper] -> [Resources] の順に指定できます。Finder では、プロジェクトのルート ディレクトリにある Classes ディレクトリと Assets ディレクトリにあります。
これらのファイルやフォルダをプロジェクトにドラッグします。[Copy items to destination group's folder] オプションが選択されていることを確認します。Assets フォルダをドラッグする場合は、[Add folders for Folder References] オプションを必ず確認してください。
これで、ライブラリのインストールが完了しました。
Interface Builder またはストーリーボードを使用して YTPlayerView
を追加する
Interface Builder またはストーリーボードを使って YTPlayerView
を追加するには:
-
UIView
インスタンスをビューにドラッグします。
-
Identity Inspector を選択して、ビューのクラスを YTPlayerView
に変更します。
-
ViewController.h
を開き、次のヘッダーを追加します。
#import “YTPlayerView.h”
また、次のプロパティも追加します。
@property(nonatomic, strong) IBOutlet YTPlayerView *playerView;
-
Interface Builder で、前のステップで定義した View 要素から View Controller の playerView
プロパティへの接続を作成します。
-
ViewController.m
を開き、viewDidLoad
メソッドの最後に次のコードを追加します。
[self.playerView loadWithVideoId:@"M7lc1UVf-VE"];
アプリをビルドして実行すると、動画のサムネイルが読み込まれたら、動画のサムネイルをタップして全画面の動画プレーヤーを起動します。
動画の再生を管理する
ViewController::loadWithVideoId:
メソッドには、loadWithVideoId:playerVars:
というバリアントがあり、デベロッパーは追加のプレーヤー変数をビューに渡すことができます。これらのプレーヤー変数は、IFrame Player API のプレーヤー パラメータに対応しています。playsinline
パラメータを使用すると、動画を全画面表示ではなく、ビューで直接再生できます。動画がインラインで再生される場合、含まれている iOS アプリはプログラムで再生を制御できます。
loadWithVideoId:
呼び出しを次のコードに置き換えます。
NSDictionary *playerVars = @{
@"playsinline" : @1,
};
[self.playerView loadWithVideoId:@"M7lc1UVf-VE" playerVars:playerVars];
ストーリーボードまたはインターフェース ビルダーを開きます。2 つのボタンをビューにドラッグし、[Play] と [Stop] というラベルを付けます。ViewController.h
を開き、次のメソッドを追加して、ボタンにマッピングされるようにします。
- (IBAction)playVideo:(id)sender;
- (IBAction)stopVideo:(id)sender;
ViewController.m
を開き、次の 2 つの関数を定義します。
- (IBAction)playVideo:(id)sender {
[self.playerView playVideo];
}
- (IBAction)stopVideo:(id)sender {
[self.playerView stopVideo];
}
ほとんどの IFrame Player API 関数には Objective-C の同等の機能がありますが、一部の命名は Objective-C のコーディング ガイドラインにより近い場合があります。注目すべき例外は、動画の音量を制御するメソッドです。これは、スマートフォンのハードウェア、またはこの目的のために設計された UIView
インスタンス(MPVolumeView
など)によって制御されます。
ストーリーボードまたはインターフェース ビルダーを開き、Ctrl キーを押しながらドラッグして、[Play] ボタンと [Stop] ボタンを playVideo:
メソッドと stopVideo:
メソッドに接続します。
アプリケーションをビルドして実行します。動画のサムネイルが読み込まれると、プレーヤー コントロールに加えてネイティブ コントロールを使用して、動画を再生、停止できるようになります。
プレーヤーのコールバックを処理する
再生状態の変更や再生エラーなどの再生イベントをプログラムで処理しておくと便利です。JavaScript API では、イベント リスナーを使用します。Objective-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
をご覧ください。
ベスト プラクティスと制限事項
ライブラリは、WebView
を作成し、基本的なプレーヤーに必要な HTML と JavaScript をレンダリングすることで、IFrame Player API の上に構築されます。ライブラリの目標は、可能な限り使いやすく、デベロッパーがパッケージに書き込む必要のあるメソッドをバンドル化することです。注意すべき制限がいくつかあります。
- このライブラリは、複数の
YTPlayerView
インスタンスでの動画の同時再生をサポートしていません。アプリケーションに YTPlayerView
インスタンスが複数ある場合は、別のインスタンスで再生を開始する前に、既存のインスタンスで再生を一時停止または停止することをおすすめします。プロジェクトに付属するサンプル アプリケーションでは、ViewController は、NSNotificationCenter
を使用して再生が開始される通知をディスパッチします。他の ViewController は、YTPlayerView
インスタンスで通知され、再生を一時停止します。
- 可能な限り、既存の読み込み済み
YTPlayerView
インスタンスを再利用します。ビュー内の動画を変更する必要がある場合は、新しい UIView
インスタンスまたは新しい YTPlayerView
インスタンスを作成しないでください。また、loadVideoId:
または loadPlaylistId:
を呼び出さないでください。代わりに、WebView
を再読み込みしない cueVideoById:startSeconds:
ファミリーの関数を使用してください。IFrame プレーヤー全体の読み込みで顕著な遅延が生じています。
- このプレーヤーは非公開の動画を再生できませんが、限定公開動画は再生できます。このライブラリは既存の iframe プレーヤーをラップしているため、プレーヤーの動作はモバイル ブラウザ内のウェブページに埋め込まれたプレーヤーとほぼ同じになります。
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 4.0 ライセンスにより使用許諾されます。コードサンプルは Apache 2.0 ライセンスにより使用許諾されます。詳しくは、Google Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
最終更新日 2023-02-22 UTC。
[[["わかりやすい","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 UTC。"],[[["\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)."]]