تضمين فيديوهات YouTube في تطبيقات iOS مع مكتبة مساعد YouTube
تنظيم صفحاتك في مجموعات
يمكنك حفظ المحتوى وتصنيفه حسب إعداداتك المفضّلة.
youtube-ios-player-helper
هي مكتبة مفتوحة المصدر تساعدك على تضمين مشغّل YouTube iframe
في تطبيق iOS. تنشئ المكتبة
WebView
وجسرًا بين رمز الهدف ج لتطبيقك
ورمز JavaScript في مشغّل YouTube، ما يسمح لتطبيق iOS بالتحكم في
مشغّل YouTube. توضح هذه المقالة خطوات تثبيت المكتبة والبدء في استخدامها من تطبيق iOS.
تثبيت
تفترض هذه المقالة أنك أنشأت مشروعًا جديدًا لتطبيق العرض الفردي على iOS يستهدف
أحدث إصدار من iOS، وأنك أضفت الملفات التالية عند إنشاء
المشروع:
Main.storyboard
ViewController.h
ViewController.m
يمكنك تثبيت المكتبة من خلال
CocoaPods أو من خلال نسخ المكتبة
والملفات المصدر من
صفحة المشروع على GitHub.
- المكتبة متاحة للتثبيت عبر CocoaPods. بدلاً من ذلك، تتوفّر المكتبة وملفات المصدر
عبر صفحة المشروع على GitHub ويمكن نسخها إلى
مشروع حالي.
تثبيت المكتبة عبر CocoaPods
إذا كان مشروعك يستخدم CocoaPods، أضِف السطر أدناه إلى Podfile لتثبيت المكتبة.
في هذا السطر، استبدِل x.y.z
بأحدث إصدار من اللوحة، والذي سيتم تحديده
على صفحة المشروع على GitHub.
pod "youtube-ios-player-helper", "~> x.y.z"
في موجه سطر الأوامر، اكتب pod install
لتعديل مساحة العمل باستخدام التبعيات.
ملاحظة: عند استخدام CocoaPods، يجب فتح ملف .xcworkspace
في Xcode، وليس ملف .xcodeproj
.
يمكنك الاطّلاع على البرنامج التعليمي CocoaPods لمعرفة المزيد من المعلومات.
تثبيت المكتبة يدويًا
لتثبيت المكتبة المساعدة يدويًا، يمكنك إما تنزيل المصدر عبر رابط تنزيل GitHub أو إنشاء نسخة طبق الأصل من المستودع. بعد الحصول على نسخة محلية من الشفرة، اتبع الخطوات التالية:
افتح نموذج المشروع في Xcode أو Finder.
اختَر YTPlayerView.h
وYTPlayerView.m
ومجلد
مواد العرض. إذا فتحت مساحة العمل في Xcode، تكون متاحة ضمن اللوحات -> لوحات التطوير -> YouTube-Player-iOS-Helper واللوحات -> لوحات التطوير -> YouTube-Player-iOS-Helper -> الموارد. في Finder (الباحث)، تتوفّر هذه المعلومات في الدليل الجذري للمشروع في دليلَي الصفوف ومواد العرض.
اسحب هذه الملفات والمجلدات إلى مشروعك. تأكّد من تحديد الخيار نسخ العناصر إلى
مجلد المجموعة الوجهة. عند سحب مجلد مواد العرض، تأكّد من وضع علامة في الخيار إنشاء مراجع مجلد لأي مجلدات مضافة.
من المفترض أن يتم تثبيت المكتبة الآن.
إضافة YTPlayerView
من خلال واجهة الواجهة أو لوحة العمل
لإضافة YTPlayerView
عبر أداة إنشاء الواجهة أو لوحة العمل:
-
اسحب مثيل UIView
إلى ملفك الشخصي.
-
اختَر أداة فحص الهوية وغيِّر فئة الملف الشخصي إلى YTPlayerView
.
-
افتح ViewController.h
وأضف الرأس التالي:
#import “YTPlayerView.h”
إضافة الموقع التالي أيضًا:
@property(nonatomic, strong) IBOutlet YTPlayerView *playerView;
-
في أداة إنشاء الواجهة، يمكنك إنشاء اتصال من عنصر العرض الذي حدَّدته في
الخطوة السابقة إلى الخاصية playerView
الخاصة بوحدة التحكُّم في الملف الشخصي.
-
افتح الآن ViewController.m
وأضِف الرمز التالي في نهاية طريقة viewDidLoad
:
[self.playerView loadWithVideoId:@"M7lc1UVf-VE"];
إنشاء تطبيقك وتشغيله. عند تحميل الصورة المصغّرة للفيديو، انقر على الصورة المصغّرة للفيديو
لتشغيل مشغّل الفيديو بملء الشاشة.
التحكم في تشغيل الفيديو
تتضمّن الطريقة ViewController::loadWithVideoId:
صيغة، وهي loadWithVideoId:playerVars:
، تسمح لمطوّري البرامج بتمرير متغيّرات إضافية في المشغّل إلى العرض. تتوافق متغيرات المشغّل هذه مع
معلّمات المشغّلات في
واجهة برمجة تطبيقات مشغّل IFrame. تتيح المَعلمة 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 على مكافِئات للالهدف ج، على الرغم من أنّ بعض أسماء الأسماء قد تختلف قليلاً عن تلك الواردة في تلك الإرشادات. وهناك استثناءات
بارزة وهي الطرق التي تتحكّم في مستوى صوت الفيديو، بما أنّها تتحكّم فيها
أجهزة الهاتف أو تتضمّن مثيلات UIView
مضمّنة مصمّمة لهذا الغرض،
مثل MPVolumeView
.
افتح لوحة العمل أو أداة إنشاء الواجهة، واسحب عنصر التحكّم لربط الزرين تشغيل وإيقاف بالطريقتين playVideo:
وstopVideo:
.
يمكنك الآن إنشاء التطبيق وتشغيله. بعد تحميل الصورة المصغّرة للفيديو، من المفترض أن تتمكن من تشغيل الفيديو وإيقافه باستخدام عناصر التحكم الأصلية بالإضافة إلى عناصر التحكم في المشغّل.
التعامل مع عمليات معاودة الاتصال بالمشغّل
وقد يكون من المفيد معالجة أحداث التشغيل آليًا، مثل تغييرات حالة التشغيل وأخطاء التشغيل. في واجهة برمجة تطبيقات JavaScript، يتم ذلك باستخدام أدوات معالجة أحداث.
في الهدف ج، يتم ذلك من خلال تفويض.
يعرض الرمز التالي كيفية تعديل بيان الواجهة في
ViewController.h
بحيث تتوافق الفئة مع بروتوكول التفويض. غيّر إعلان واجهة ViewController.h
على النحو التالي:
@interface ViewController : UIViewController<YTPlayerViewDelegate>
YTPlayerViewDelegate
عبارة عن بروتوكول لمعالجة أحداث التشغيل في المشغّل.
لتعديل ViewController.m
للتعامل مع بعض الأحداث، عليك أولاً ضبط
مثيل ViewController
كمفوّض لمثيل YTPlayerView
. لإجراء هذا التغيير، أضِف السطر التالي إلى طريقة viewDidLoad
في ViewController.h
.
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 من خلال إنشاء WebView
وعرض HTML وجافا سكريبت المطلوبَين للمشغل الأساسي. إنّ الهدف من المكتبة هو توفير
طرق سهلة الاستخدام قدر الإمكان، بحيث يكون على مطوّري البرامج كتابتها في حزمة
بسهولة. وهناك بعض القيود التي يجب ملاحظتها:
- لا تتيح المكتبة تشغيل الفيديو المتزامن في نُسخ متعددة من
YTPlayerView
. إذا كان تطبيقك يتضمّن عدّة مثيلات من YTPlayerView
، من أفضل الممارسات المقترَحة إيقاف التشغيل مؤقتًا أو إيقافه في أي مثيلات حالية قبل بدء التشغيل في مثيل آخر. في نموذج التطبيق الذي يتم شحنه مع المشروع، تستفيد وحدات التحكم في العرض من NSNotificationCenter
لإرسال إشعارات بأن عملية التشغيل على وشك البدء. يتم إرسال إشعارات إلى وحدات التحكم الأخرى في المشاهدة وسيتم إيقاف التشغيل مؤقتًا في مثيلاتها من أجهزة YTPlayerView
.
- أعِد استخدام مثيلات
YTPlayerView
الحالية التي تم تحميلها، إن أمكن. عندما تحتاج إلى تغيير فيديو في طريقة عرض، لا تنشئ مثيل UIView
جديدًا أو مثيل YTPlayerView
جديد، ولا تستدعي loadVideoId:
أو loadPlaylistId:
. وبدلاً من ذلك، يمكنك استخدام مجموعة الدوال cueVideoById:startSeconds:
التي لا تعيد تحميل WebView
. يحدث تأخر ملحوظ عند تحميل
مشغل IFrame بالكامل.
- يتعذر على هذا المشغل تشغيل مقاطع فيديو خاصة، ولكن يمكنه تشغيل
مقاطع فيديو غير مدرجة. وبما أنّ هذه المكتبة تغطي مشغّل iframe الحالي، يجب أن يكون سلوك المشغّل متطابقًا تقريبًا
مع سلوك المشغّل المضمّن في صفحة ويب في متصفّح متوافق مع الأجهزة الجوّالة.
إنّ محتوى هذه الصفحة مرخّص بموجب ترخيص Creative Commons Attribution 4.0 ما لم يُنصّ على خلاف ذلك، ونماذج الرموز مرخّصة بموجب ترخيص Apache 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)."]]