Nhúng video trên YouTube trong ứng dụng iOS bằng Thư viện trợ giúp YouTube
Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
youtube-ios-player-helper
là một thư viện nguồn mở giúp bạn nhúng trình phát iframe của YouTube vào ứng dụng iOS. Thư viện sẽ tạo
WebView
và là cầu nối giữa mã Objective-C của ứng dụng với
mã JavaScript của trình phát YouTube, qua đó cho phép ứng dụng iOS kiểm soát
trình phát YouTube. Bài viết này mô tả các bước cài đặt thư viện và bắt đầu
sử dụng thư viện đó trong ứng dụng iOS.
Cài đặt
Bài viết này giả định bạn đã tạo một dự án iOS duy nhất cho Ứng dụng Chế độ xem đơn nhắm đến phiên bản iOS mới nhất và bạn cũng thêm các tệp sau đây khi tạo dự án:
Main.storyboard
ViewController.h
ViewController.m
Bạn có thể cài đặt thư viện thông qua CocoaPods hoặc bằng cách sao chép thư viện và các tệp nguồn từ trang GitHub của dự án.
- Bạn có thể cài đặt thư viện này qua CocoaPods. Ngoài ra, thư viện và các tệp nguồn có sẵn thông qua trang GitHub của dự án và có thể được sao chép vào một dự án hiện có.
Cài đặt thư viện qua CocoaPods
Nếu dự án của bạn sử dụng CocoaPods, hãy thêm dòng bên dưới vào Podfile để cài đặt thư viện.
Trong dòng đó, hãy thay thế x.y.z
bằng phiên bản nhóm mới nhất sẽ được xác định trên trang GitHub của dự án.
pod "youtube-ios-player-helper", "~> x.y.z"
Khi được nhắc dòng lệnh, hãy nhập pod install
để cập nhật không gian làm việc bằng các phần phụ thuộc.
Lưu ý: Hãy nhớ rằng khi sử dụng CocoaPods, bạn phải mở tệp .xcworkspace
trong Xcode chứ không phải tệp .xcodeproj
.
Hãy xem hướng dẫn về
CocoaPods để tìm hiểu thêm.
Cài đặt thư viện theo cách thủ công
Để cài đặt thư viện trợ giúp theo cách thủ công, hãy tải nguồn xuống qua
đường liên kết tải xuống của GitHub hoặc
sao chép kho lưu trữ. Sau khi có bản sao cục bộ của mã, hãy làm theo các bước sau:
Mở dự án mẫu trong Xcode hoặc Finder.
Chọn YTPlayerView.h
, YTPlayerView.m
và thư mục
Assets (Tài sản). Nếu bạn mở không gian làm việc trong Xcode, những không gian làm việc này sẽ có trong
Pods -> Development Pods -> YouTube-Player-iOS-Helper và
Pods -> Development Pods -> YouTube-Player-iOS-Helper -> Resources. Trong Finder (Trình tìm kiếm), các tệp này có trong thư mục gốc của dự án trong thư mục Classes (Lớp) và Assets (Tài sản).
Kéo các tệp và thư mục này vào dự án của bạn. Đảm bảo rằng bạn đã đánh dấu chọn tuỳ chọn Sao chép các mục vào
thư mục của nhóm đích đến. Khi kéo thư mục Assets (Thành phần), hãy nhớ đánh dấu vào tuỳ chọn Create Folder Reference for any added directory (Tạo tệp tham chiếu thư mục cho mọi thư mục đã thêm).
Thư viện hiện đã được cài đặt.
Thêm YTPlayerView
thông qua Trình tạo giao diện hoặc Bảng phân cảnh
Cách thêm YTPlayerView
thông qua Trình tạo giao diện hoặc Bảng phân cảnh:
-
Kéo một thực thể UIView
vào Chế độ xem của bạn.
-
Chọn Trình kiểm tra danh tính và thay đổi lớp thành phần hiển thị thành YTPlayerView
.
-
Mở ViewController.h
và thêm tiêu đề sau:
#import “YTPlayerView.h”
Ngoài ra, hãy thêm thuộc tính sau:
@property(nonatomic, strong) IBOutlet YTPlayerView *playerView;
-
Trong Trình tạo giao diện, hãy tạo một kết nối từ phần tử Chế độ xem mà bạn đã xác định ở bước trước
với thuộc tính playerView
của Trình điều khiển chế độ xem.
-
Bây giờ, hãy mở ViewController.m
và thêm mã sau vào cuối phương thức viewDidLoad
:
[self.playerView loadWithVideoId:@"M7lc1UVf-VE"];
Tạo bản dựng và chạy ứng dụng của bạn. Khi hình thu nhỏ của video tải, hãy nhấn vào hình thu nhỏ video để chạy trình phát video toàn màn hình.
Điều khiển chế độ phát video
Phương thức ViewController::loadWithVideoId:
có một biến thể là
loadWithVideoId:playerVars:
cho phép các nhà phát triển chuyển thêm biến biến người chơi
vào thành phần hiển thị. Các biến trình phát này tương ứng với các thông số về trình phát trong API IFrame Player. Tham số playsinline
cho phép video phát trực tiếp trong thành phần hiển thị thay vì phát toàn màn hình. Khi video đang phát tại chỗ, ứng dụng chứa iOS có thể được lập trình để điều khiển chế độ phát.
Thay thế lệnh gọi loadWithVideoId:
bằng mã sau:
NSDictionary *playerVars = @{
@"playsinline" : @1,
};
[self.playerView loadWithVideoId:@"M7lc1UVf-VE" playerVars:playerVars];
Mở bảng phân cảnh hoặc Trình tạo giao diện. Kéo hai nút vào Chế độ xem của bạn, gắn nhãn đó là Phát và Dừng. Mở ViewController.h
và thêm các phương thức sau đây
để liên kết với các nút:
- (IBAction)playVideo:(id)sender;
- (IBAction)stopVideo:(id)sender;
Bây giờ, hãy mở ViewController.m
và xác định hai hàm này:
- (IBAction)playVideo:(id)sender {
[self.playerView playVideo];
}
- (IBAction)stopVideo:(id)sender {
[self.playerView stopVideo];
}
Hầu hết chức năng API Trình phát IFrame đều có các tham số tương đương Objective-C, mặc dù một số
tên gọi có thể hơi khác một chút để phù hợp hơn với các nguyên tắc lập trình Objective-C. Đáng chú ý là các trường hợp ngoại lệ là các phương thức kiểm soát âm lượng của video, vì các phần tử này chịu sự kiểm soát của phần cứng điện thoại hoặc được tích hợp sẵn các thực thể UIView
nhằm mục đích này, chẳng hạn như MPVolumeView
.
Mở bảng phân cảnh hoặc Trình tạo giao diện và kéo-kéo để kết nối nút Phát và
Dừng với phương thức playVideo:
và stopVideo:
.
Bây giờ, hãy tạo và chạy ứng dụng. Sau khi hình thu nhỏ của video tải, bạn có thể phát và dừng video bằng cách sử dụng các nút điều khiển gốc bên cạnh các nút điều khiển trình phát.
Xử lý lệnh gọi lại của người chơi
Việc này có thể giúp bạn xử lý các sự kiện phát theo phương thức lập trình, chẳng hạn như các thay đổi về trạng thái phát và lỗi phát. Trong API JavaScript, việc này được thực hiện bằng trình nghe sự kiện.
Trong Objective-C,việc này được thực hiện bằng một
đại biểu.
Mã sau đây cho biết cách cập nhật phần khai báo giao diện trong ViewController.h
để lớp tuân thủ giao thức uỷ quyền. Thay đổi phần khai báo giao diện của ViewController.h
như sau:
@interface ViewController : UIViewController<YTPlayerViewDelegate>
YTPlayerViewDelegate
là một giao thức để xử lý các sự kiện phát trong trình phát.
Để cập nhật ViewController.m
nhằm xử lý một số sự kiện, trước tiên, bạn cần đặt giá trị cho thực thể ViewController
làm thực thể đại diện của thực thể YTPlayerView
. Để thực hiện thay đổi này, hãy thêm dòng sau vào phương thức viewDidLoad
trong ViewController.h
.
self.playerView.delegate = self;
Bây giờ, hãy thêm phương thức sau vào 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;
}
}
Tạo và chạy ứng dụng Xem kết quả nhật ký trong Xcode khi trạng thái của người chơi thay đổi.
Bạn sẽ nhìn thấy thông tin cập nhật khi phát hoặc dừng video.
Thư viện cung cấp các hằng số bắt đầu bằng tiền tố kYT*
để thuận tiện và dễ đọc. Để nắm được danh sách đầy đủ các hằng số này, hãy xem YTPlayerView.m
.
Các phương pháp hay nhất và hạn chế
Thư viện này được xây dựng dựa trên API IFrame Player bằng cách tạo một WebView
và kết xuất HTML và JavaScript bắt buộc cho một trình phát cơ bản. Mục tiêu của thư viện này là càng dễ sử dụng càng tốt, gói các phương thức mà nhà phát triển thường phải viết vào một gói. Sau đây là một số hạn chế cần lưu ý:
- Thư viện này không hỗ trợ tính năng phát video đồng thời trong nhiều
bản sao
YTPlayerView
. Nếu ứng dụng có nhiều thực thể YTPlayerView
, bạn nên tạm dừng hoặc dừng phát trong mọi thực thể hiện có trước khi bắt đầu phát trong một thực thể khác. Trong
ứng dụng mẫu đi kèm với dự án, ViewControllers sử dụng
NSNotificationCenter
để gửi thông báo mà quá trình phát
sắp bắt đầu. Các ViewController khác sẽ nhận được thông báo và sẽ tạm dừng phát trong các thực thể
YTPlayerView
của chúng.
- Sử dụng lại các phiên bản
YTPlayerView
đã tải hiện có khi có thể. Khi bạn cần thay đổi một video trong một Chế độ xem, đừng tạo bản sao UIView
mới hoặc bản sao YTPlayerView
mới và đừng gọi loadVideoId:
hoặc loadPlaylistId:
. Thay vào đó, hãy sử dụng nhóm hàm cueVideoById:startSeconds:
, các hàm này không tải lại WebView
. Có một độ trễ đáng kể khi tải toàn bộ
trình phát IFrame.
- Trình phát này không thể phát video riêng tư nhưng có thể phát video không công khai. Vì thư viện này bao bọc trình phát iframe hiện có, nên hành vi của trình phát này gần giống với hành vi của trình phát được nhúng trên trang web trong trình duyệt cho thiết bị di động.
Trừ phi có lưu ý khác, nội dung của trang này được cấp phép theo Giấy phép ghi nhận tác giả 4.0 của Creative Commons và các mẫu mã lập trình được cấp phép theo Giấy phép Apache 2.0. Để biết thông tin chi tiết, vui lòng tham khảo Chính sách trang web của Google Developers. Java là nhãn hiệu đã đăng ký của Oracle và/hoặc các đơn vị liên kết với Oracle.
Cập nhật lần gần đây nhất: 2023-02-22 UTC.
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 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)."]]