使用 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 中,这些内容位于项目的根目录中的 Classes 和 Assets 目录中。
将这些文件和文件夹拖到您的项目中。确保已选中 Copy items into destination group's folder 选项。拖动素材资源文件夹时,请务必选中为所有已添加的文件夹创建文件夹引用选项。
现在,应安装该库。
通过 Interface Builder 或 Storyboard 添加 YTPlayerView
如需通过 Interface Builder 或 Storyboard 添加 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];
打开 Storyboard 或 Interface Builder。将两个按钮拖动到您的视图,分别标记为播放和停止。打开 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
)。
打开您的 Storyboard 或 Interface Builder 并按住拖动鼠标,将 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
。
最佳做法和限制
该库基于 IFrame Player API 构建,方法是创建 WebView
并呈现基本播放器所需的 HTML 和 JavaScript。该库的目标是尽可能易于使用,捆绑开发者经常必须编写到软件包中的方法。需要注意一些限制:
- 该库不支持在多个
YTPlayerView
实例中并发播放视频。如果您的应用有多个 YTPlayerView
实例,建议您先暂停或停止任何现有实例中的播放,然后再在其他实例中开始播放。在项目随附的示例应用中,ViewController 使用 NSNotificationCenter
分派即将开始播放的通知。其他 ViewController 将收到通知,并将在其 YTPlayerView
实例中暂停播放。
- 尽可能重复使用已加载的现有
YTPlayerView
实例。如果需要在视图中更改视频,请勿创建新的 UIView
实例或新的 YTPlayerView
实例,也不要调用 loadVideoId:
或 loadPlaylistId:
。请改为使用不会重新加载 WebView
的 cueVideoById:startSeconds:
系列的函数。加载整个 iframe 播放器时会有明显的延迟。
- 此播放器无法播放私享视频,但可以播放不公开列出的视频。由于此库会封装现有 iframe 播放器,因此该播放器的行为应该与移动浏览器中嵌入网页的播放器的行为几乎相同。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):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"]],["最后更新时间 (UTC):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)."]]