YouTube Yardımcı Kitaplığı ile YouTube Videolarını iOS Uygulamalarına Yerleştirme
Koleksiyonlar ile düzeninizi koruyun
İçeriği tercihlerinize göre kaydedin ve kategorilere ayırın.
youtube-ios-player-helper
, bir YouTube iframe oynatıcıyı iOS uygulamasına yerleştirmenize yardımcı olan bir açık kaynak kitaplığıdır. Kitaplık, uygulamanızın Object-C kodu ile YouTube oynatıcısının JavaScript kodu arasında bir WebView
ve köprü oluşturur. Böylece iOS uygulamasının YouTube oynatıcısını kontrol etmesi sağlanır. Bu makalede, kitaplığı yükleme ve iOS uygulamanızdan kullanmaya başlama adımları açıklanmaktadır.
Kurulum
Bu makalede, iOS'in en son sürümünü hedefleyen yeni bir Tek Görüntüleme Uygulaması iOS projesi oluşturduğunuz ve projeyi oluştururken aşağıdaki dosyaları eklediğiniz varsayılmaktadır:
Main.storyboard
ViewController.h
ViewController.m
Kitaplığı, CocoaPods aracılığıyla veya projenin GitHub sayfasındaki kitaplık ve kaynak dosyalarını kopyalayarak yükleyebilirsiniz.
- Kitaplık, CocoaPods üzerinden yüklenebilir. Kitaplık ve kaynak dosyaları, projenin GitHub sayfasından da mevcuttur ve mevcut bir projeye kopyalanabilir.
Kitaplığı CocoaPods üzerinden yükleme
Projeniz CocoaPods kullanıyorsa kitaplığı yüklemek için aşağıdaki satırı Podfile dosyanıza ekleyin.
Bu satırda x.y.z
değerini, projenin GitHub sayfasında tanımlanan en son kapsül sürümüyle değiştirin.
pod "youtube-ios-player-helper", "~> x.y.z"
Çalışma alanınızı bağımlılıklarla güncellemek için komut satırı isteminde pod install
yazın.
İpucu: CocoaPods kullanırken .xcworkspace
dosyasını .xcodeproj
dosyası yerine Xcode'da açmanız gerekir.
Daha fazla bilgi için CocoaPods eğitimine göz atın.
Kitaplığı manuel olarak yükleme
Yardımcı kitaplığı manuel olarak yüklemek için kaynağı GitHub'ın indirme bağlantısı aracılığıyla indirin veya depoyu klonlayın. Kodun yerel bir kopyasına sahip olduğunuzda aşağıdaki adımları uygulayın:
Xcode veya Finder'da örnek projeyi açın.
YTPlayerView.h
, YTPlayerView.m
ve Öğeler klasörünü seçin. Çalışma alanını Xcode'da açarsanız bunları Pods -> Geliştirme Kapsülleri -> YouTube-Player-iOS-Yardımcısı ve Pods -> Geliştirme Kapsülleri -> YouTube-Player-iOS-Yardımcı -> Kaynaklar bölümlerinde bulabilirsiniz. Finder'da, bunlar Sınıflar ve Öğeler dizinlerinde projenin kök dizininde bulunur.
Bu dosya ve klasörleri projenize sürükleyin. Öğeleri hedef grubun klasörüne kopyala seçeneğinin işaretli olduğundan emin olun. Öğeler klasörünü sürüklerken Eklenen klasörler için Klasör Referansları oluşturun seçeneğinin işaretli olduğundan emin olun.
Kitaplık artık yüklenmiş olmalıdır.
Arayüz Oluşturucu veya Resimli Taslak aracılığıyla YTPlayerView
ekleyin
Arayüz Oluşturucu veya Resimli Taslak üzerinden YTPlayerView
eklemek için:
-
Görünümünüze bir UIView
örneği sürükleyin.
-
Kimlik İnceleyici'yi seçin ve görünümü YTPlayerView
olarak değiştirin.
-
ViewController.h
öğesini açın ve aşağıdaki üstbilgiyi ekleyin:
#import “YTPlayerView.h”
Ayrıca, aşağıdaki özelliği ekleyin:
@property(nonatomic, strong) IBOutlet YTPlayerView *playerView;
-
Arayüz Oluşturucu'da, önceki adımda görüntülediğiniz Görünüm öğesinden, Görünüm Denetleyicinizin playerView
mülküne bir bağlantı oluşturun.
-
Şimdi ViewController.m
uygulamasını açıp aşağıdaki kodu viewDidLoad
yönteminizin sonuna ekleyin:
[self.playerView loadWithVideoId:@"M7lc1UVf-VE"];
Uygulamanızı oluşturup çalıştırın. Video küçük resmi yüklendiğinde, tam ekran video oynatıcıyı başlatmak için video küçük resmine dokunun.
Video oynatmayı kontrol etme
ViewController::loadWithVideoId:
yönteminin, geliştiricilerin görünüme ek oyuncu değişkenleri iletmesini sağlayan bir varyant (loadWithVideoId:playerVars:
) vardır. Bu oynatıcı değişkenleri, IFrame Player API'sindeki oynatıcı parametrelerine karşılık gelir. playsinline
parametresi, videonun tam ekranda oynatılması yerine doğrudan görünümde oynatılmasını sağlar. Bir video satır içinde oynatılırken videoyu içeren uygulama, oynatmayı programatik olarak kontrol edebilir.
loadWithVideoId:
çağrısını bu kodla değiştirin:
NSDictionary *playerVars = @{
@"playsinline" : @1,
};
[self.playerView loadWithVideoId:@"M7lc1UVf-VE" playerVars:playerVars];
Resimli taslakı veya Arayüz Oluşturucu'yu açın. İki düğmeyi Görünümünüze sürükleyerek Oynat ve Durdur şeklinde etiketleyin. ViewController.h
öğesini açın ve düğmelerle eşlenecek aşağıdaki yöntemleri ekleyin:
- (IBAction)playVideo:(id)sender;
- (IBAction)stopVideo:(id)sender;
Şimdi ViewController.m
öğesini açın ve şu iki işlevi tanımlayın:
- (IBAction)playVideo:(id)sender {
[self.playerView playVideo];
}
- (IBAction)stopVideo:(id)sender {
[self.playerView stopVideo];
}
IFrame Player API'nin işlevlerinin çoğunda Object-C eşdeğerleri olsa da adlandırmadan
bazıları Objective-C kodlama yönergeleriyle daha yakından eşleşecek şekilde farklılık gösterebilir. Telefon donanımı tarafından veya bu amaç için tasarlanmış yerleşik UIView
örneklerinde (MPVolumeView
gibi) kontrol edildiği için videonun hacmini kontrol eden yöntemler istisnadır.
Resimli taslakınızı veya Arayüz Oluşturucu'nuzu açın ve Oynat ile Durdur düğmelerini playVideo:
ve stopVideo:
yöntemlerine bağlamak için sürükleyin.
Şimdi uygulamayı derleyip çalıştırın. Video küçük resmi yüklendiğinde, oynatıcı kontrollerine ek olarak yerel kontrolleri kullanarak videoyu oynatabilmeniz ve durdurabilmeniz gerekir.
Oyuncu geri çağırmalarını işleme
Oynatma durumu değişiklikleri ve oynatma hataları gibi oynatma etkinliklerini programatik olarak yönetmek faydalı olabilir. JavaScript API'sinde bu işlem etkinlik işleyicilerle yapılır.
Objective-C'de bu bir yetki ile yapılır.
Aşağıdaki kod, sınıfın yetki verilen protokole uygun olması için ViewController.h
'deki arayüz beyanının nasıl güncelleneceğini gösterir. ViewController.h
arayüzü beyanını aşağıdaki gibi değiştirin:
@interface ViewController : UIViewController<YTPlayerViewDelegate>
YTPlayerViewDelegate
, oynatıcıdaki oynatma etkinliklerinin işlenmesine yönelik bir protokoldür.
Bazı etkinlikleri işlemek için ViewController.m
uygulamasını güncellemek üzere ilk olarak ViewController
örneğini YTPlayerView
örneğinin yetkilisi olarak ayarlamanız gerekir. Bu değişikliği yapmak için aşağıdaki satırı ViewController.h
içinde viewDidLoad
yöntemine ekleyin.
self.playerView.delegate = self;
Şimdi ViewController.m
yöntemini şu yöntemi ekleyin:
- (void)playerView:(YTPlayerView *)playerView didChangeToState:(YTPlayerState)state {
switch (state) {
case kYTPlayerStatePlaying:
NSLog(@"Started playback");
break;
case kYTPlayerStatePaused:
NSLog(@"Paused playback");
break;
default:
break;
}
}
Uygulamayı oluşturun ve çalıştırın. Oynatıcı durumu değiştikçe Xcode'daki günlük çıkışını izleyin.
Video oynatıldığında veya durdurulduğunda güncellemeleri görürsünüz.
Kitaplık, kolaylık ve okunabilirlik için kYT*
ön ekiyle başlayan sabit değerler sağlar. Bu sabitlerin tam listesi için YTPlayerView.m
sayfasına bakın.
En iyi uygulamalar ve sınırlamalar
Kitaplık, WebView
çerçevesi oluşturup temel oynatıcı için gereken HTML ve JavaScript'i oluşturarak IFrame Player API'sinin üzerine inşa edilir. Kitaplığın hedefi, geliştiricilerin bir pakete sık sık yazması gereken, mümkün olduğunca kolay kullanılan bir yöntemdir. Dikkat edilmesi gereken birkaç sınırlama var:
- Kitaplık, birden fazla
YTPlayerView
örneğinde aynı anda video oynatmayı desteklemez. Uygulamanızda birden fazla YTPlayerView
örneği varsa farklı bir örnekte oynatmaya başlamadan önce mevcut örneklerin oynatılmasını duraklatmak veya durdurmak önerilir. Projeyle birlikte gönderilen örnek uygulamada ViewController'lar, oynatmanın başlayacağına dair bildirimleri göndermek için NSNotificationCenter
kullanır. Diğer ViewController kullanıcılara bildirilir ve YTPlayerView
örneklerinde oynatmayı duraklatır.
- Mümkün olduğunda mevcut
YTPlayerView
yüklü örneklerinizi yeniden kullanın. Görünümde bir videonun değiştirilmesi gerektiğinde yeni bir UIView
örneği veya yeni bir YTPlayerView
örneği oluşturmayın ve loadVideoId:
ya da loadPlaylistId:
çağrısı yapmayın. Bunun yerine, WebView
öğesini yeniden yüklemeyen cueVideoById:startSeconds:
işlev ailesini kullanın. IFrame oynatıcısının tamamı yüklenirken önemli bir gecikme olur.
- Bu oynatıcı özel video oynatamaz ancak liste dışı videoları oynatabilir. Bu kitaplık, mevcut iframe oynatıcıyı sarmaladığından oynatıcının davranışı, mobil tarayıcıda web sayfasına yerleştirilmiş bir oynatıcıyla hemen hemen aynı olmalıdır.
Aksi belirtilmediği sürece bu sayfanın içeriği Creative Commons Atıf 4.0 Lisansı altında ve kod örnekleri Apache 2.0 Lisansı altında lisanslanmıştır. Ayrıntılı bilgi için Google Developers Site Politikaları'na göz atın. Java, Oracle ve/veya satış ortaklarının tescilli ticari markasıdır.
Son güncelleme tarihi: 2023-02-22 UTC.
[[["Anlaması kolay","easyToUnderstand","thumb-up"],["Sorunumu çözdü","solvedMyProblem","thumb-up"],["Diğer","otherUp","thumb-up"]],[["İhtiyacım olan bilgiler yok","missingTheInformationINeed","thumb-down"],["Çok karmaşık / çok fazla adım var","tooComplicatedTooManySteps","thumb-down"],["Güncel değil","outOfDate","thumb-down"],["Çeviri sorunu","translationIssue","thumb-down"],["Örnek veya kod sorunu","samplesCodeIssue","thumb-down"],["Diğer","otherDown","thumb-down"]],["Son güncelleme tarihi: 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)."]]