Umieszczanie filmów z YouTube w aplikacjach na iOS przy użyciu biblioteki pomocniczej YouTube
Zadbaj o dobrą organizację dzięki kolekcji
Zapisuj i kategoryzuj treści zgodnie ze swoimi preferencjami.
youtube-ios-player-helper
to biblioteka typu open source, która ułatwia umieszczanie odtwarzacza iframe YouTube w aplikacji na iOS. Biblioteka tworzy WebView
i most między kodem celu C a kodem JavaScript odtwarzacza YouTube, pozwalając aplikacji iOS na kontrolowanie odtwarzacza YouTube. Z tego artykułu dowiesz się, jak zainstalować bibliotekę i zacząć korzystać z niej w aplikacji na iOS.
Montaż
W tym artykule zakładamy, że masz utworzony nowy projekt aplikacji na iOS z pojedynczym widokiem kierowany na najnowszą wersję iOS i że podczas tworzenia projektu dodajesz te pliki:
Main.storyboard
ViewController.h
ViewController.m
Możesz zainstalować bibliotekę za pomocą CocoaPods lub przez skopiowanie biblioteki i plików źródłowych ze strony projektu na GitHubie.
- Biblioteka jest dostępna do zainstalowania za pomocą CocoaPods. Pliki biblioteki i źródłowe są też dostępne na stronie GitHub Twojego projektu i można je skopiować do istniejącego projektu.
Instalowanie biblioteki za pomocą CocoaPods
Jeśli w projekcie używasz CocoaPods, dodaj poniższy wiersz do pliku Podfile, aby zainstalować bibliotekę.
W tym wierszu zastąp x.y.z
najnowszą wersją poda, która zostanie zidentyfikowana na stronie projektu na GitHubie.
pod "youtube-ios-player-helper", "~> x.y.z"
W wierszu poleceń wpisz pod install
, aby zaktualizować obszar roboczy zależności.
Wskazówka: jeśli używasz CocoaPods, musisz otworzyć plik .xcworkspace
w Xcode, a nie .xcodeproj
.
Więcej informacji znajdziesz w samouczku CocoaPods.
Ręczne instalowanie biblioteki
Aby zainstalować bibliotekę pomocniczą ręcznie, pobierz źródło za pomocą linku do pobrania z GitHuba lub skopiuj repozytorium. Gdy już będziesz mieć lokalną kopię kodu, wykonaj te czynności:
Otwórz przykładowy projekt w Xcode lub Finderze.
Wybierz YTPlayerView.h
, YTPlayerView.m
i folder Zasoby. Jeśli otworzysz obszar roboczy w Xcode, znajdziesz go w sekcjach Pods -> Development Pods -> YouTube-Player-iOS-Helper i Pods -> Development Pods -> YouTube-Player-iOS-Helper -> Zasoby. W Finderze znajdują się one w katalogu głównym projektu w katalogach Classes i Assets.
Przeciągnij te pliki i foldery do projektu. Upewnij się, że opcja Kopiuj elementy do folderu grupy docelowej jest zaznaczona. Podczas przeciągania folderu Zasoby sprawdź, czy jest zaznaczona opcja Utwórz odwołania do folderów dla wszystkich dodanych folderów.
Biblioteka powinna być teraz zainstalowana.
Dodaj YTPlayerView
za pomocą Kreatora interfejsów lub scenorysu
Aby dodać element YTPlayerView
za pomocą konstruktora interfejsu lub scenorysu:
-
Przeciągnij instancję UIView
do widoku.
-
Wybierz Inspektora tożsamości i zmień klasę widoku na YTPlayerView
.
-
Otwórz plik ViewController.h
i dodaj ten nagłówek:
#import “YTPlayerView.h”
Dodaj też tę właściwość:
@property(nonatomic, strong) IBOutlet YTPlayerView *playerView;
-
W Kreatorze interfejsu utwórz połączenie z elementu View zdefiniowanego w poprzednim kroku z właściwością playerView
Controller.
-
Teraz otwórz ViewController.m
i dodaj ten kod na końcu metody viewDidLoad
:
[self.playerView loadWithVideoId:@"M7lc1UVf-VE"];
skompilować i uruchomić aplikację. Po wczytaniu miniatury filmu dotknij miniatury, aby włączyć odtwarzacz wideo na pełnym ekranie.
Sterowanie odtwarzaniem filmów
Metoda ViewController::loadWithVideoId:
ma wariant loadWithVideoId:playerVars:
, który pozwala deweloperom przekazywać do widoku dodatkowe zmienne odtwarzacza. Zmienne te odpowiadają parametrom odtwarzacza w interfejsie IFrame Player API. Parametr playsinline
umożliwia odtwarzanie filmu bezpośrednio w widoku, a nie w trybie pełnoekranowym. Gdy film jest odtwarzany w treści, aplikacja zawierająca aplikację na iOS może automatycznie sterować odtwarzaniem.
Zastąp wywołanie loadWithVideoId:
tym kodem:
NSDictionary *playerVars = @{
@"playsinline" : @1,
};
[self.playerView loadWithVideoId:@"M7lc1UVf-VE" playerVars:playerVars];
Otwórz scenorys lub Kreator interfejsu. Przeciągnij 2 przyciski do widoku, przypisując mu etykietę Odtwórz i Zatrzymaj. Otwórz ViewController.h
i dodaj te metody, które zostaną zmapowane na przyciski:
- (IBAction)playVideo:(id)sender;
- (IBAction)stopVideo:(id)sender;
Teraz otwórz ViewController.m
i określ te 2 funkcje:
- (IBAction)playVideo:(id)sender {
[self.playerView playVideo];
}
- (IBAction)stopVideo:(id)sender {
[self.playerView stopVideo];
}
Większość funkcji interfejsu IFrame Player API ma swoje odpowiedniki w celu C, ale niektóre nazwy mogą się nieznacznie różnić od wytycznych dotyczących kodowania Goal-C. Wyjątkami są metody sterujące głośnością filmu, ponieważ te funkcje są kontrolowane przez sprzęt telefoniczny lub mają wbudowane wystąpienia UIView
przeznaczone do tego celu, takie jak MPVolumeView
.
Otwórz scenorys lub konstruktor interfejsu i przeciągnij go, by połączyć przyciski Odtwórz i Zatrzymaj z metodami playVideo:
i stopVideo:
.
Teraz skompiluj i uruchom aplikację. Po wczytaniu miniatury filmu powinno być możliwe odtworzenie i zatrzymanie filmu za pomocą elementów sterujących odtwarzaczem oraz elementów sterujących odtwarzaczem.
Obsługa wywołań zwrotnych odtwarzacza
Może być przydatna przy automatycznym obsłudze zdarzeń odtwarzania, takich jak zmiany stanu odtwarzania czy błędy odtwarzania. W interfejsie JavaScript API służy do tego detektory zdarzeń.
W języku celu C jest to realizowane za pomocą przekazania dostępu.
Poniższy kod pokazuje, jak zaktualizować deklarację interfejsu w ViewController.h
, aby klasa była zgodna z protokołem przekazywania. Zmień deklarację interfejsu ViewController.h
w ten sposób:
@interface ViewController : UIViewController<YTPlayerViewDelegate>
YTPlayerViewDelegate
to protokół obsługi zdarzeń odtwarzania w odtwarzaczu.
Aby można było zaktualizować ViewController.m
w celu obsługi niektórych zdarzeń, musisz najpierw skonfigurować instancję ViewController
jako przedstawiciela instancji YTPlayerView
. Aby wprowadzić tę zmianę, dodaj następujący wiersz do metody viewDidLoad
w ViewController.h
.
self.playerView.delegate = self;
Teraz dodaj do metody ViewController.m
tę metodę:
- (void)playerView:(YTPlayerView *)playerView didChangeToState:(YTPlayerState)state {
switch (state) {
case kYTPlayerStatePlaying:
NSLog(@"Started playback");
break;
case kYTPlayerStatePaused:
NSLog(@"Paused playback");
break;
default:
break;
}
}
skompilować i uruchomić aplikację. Śledź dane wyjściowe logu w Xcode, gdy zmienia się stan odtwarzacza.
Po włączeniu lub zakończeniu odtwarzania filmu powinny pojawić się aktualizacje.
Dla wygody i czytelności biblioteka zawiera stałe wartości zaczynające się od prefiksu kYT*
. Pełną listę tych stałych znajdziesz na YTPlayerView.m
.
Sprawdzone metody i ograniczenia
Biblioteka jest oparta na API IFrame Player przez utworzenie WebView
i renderowanie kodu HTML oraz JavaScript wymaganego dla podstawowego odtwarzacza. Zadaniem biblioteki jest stworzenie jak najprostszej w użyciu i połączonych metod, których programiści często muszą zapisywać w pakietach. Pamiętaj o kilku ograniczeniach:
- Biblioteka nie obsługuje jednoczesnego odtwarzania filmów w wielu instancjach
YTPlayerView
. Jeśli aplikacja ma wiele wystąpień YTPlayerView
, zaleca się wstrzymanie lub zatrzymanie odtwarzania w dowolnej z instancji, zanim rozpocznie się odtwarzanie w innej instancji. W przykładowej aplikacji dołączonej do projektu elementy ViewViewler używają NSNotificationCenter
do wysyłania powiadomień o rozpoczęciu odtwarzania. Inne kontrolery ViewControl otrzymają powiadomienia i wstrzymają odtwarzanie w swoich instancjach YTPlayerView
.
- Jeśli to możliwe, ponownie wykorzystaj istniejące, wczytane instancje
YTPlayerView
. Gdy w widoku danych trzeba zmienić film, nie twórz nowej instancji UIView
ani nowej instancji YTPlayerView
ani wywołaj właściwości loadVideoId:
lub loadPlaylistId:
. Zamiast tego użyj rodziny funkcji cueVideoById:startSeconds:
, które nie ładują ponownie WebView
. Występuje znaczne opóźnienie podczas wczytywania całego odtwarzacza IFrame.
- Ten odtwarzacz nie może odtwarzać filmów prywatnych, ale może odtwarzać filmy niepubliczne. Ponieważ ta biblioteka otacza istniejący odtwarzacz iframe, jego działanie powinno być niemal takie samo jak w przypadku odtwarzacza umieszczonego na stronie internetowej w przeglądarce mobilnej.
O ile nie stwierdzono inaczej, treść tej strony jest objęta licencją Creative Commons – uznanie autorstwa 4.0, a fragmenty kodu są dostępne na licencji Apache 2.0. Szczegółowe informacje na ten temat zawierają zasady dotyczące witryny Google Developers. Java jest zastrzeżonym znakiem towarowym firmy Oracle i jej podmiotów stowarzyszonych.
Ostatnia aktualizacja: 2023-02-22 UTC.
[[["Łatwo zrozumieć","easyToUnderstand","thumb-up"],["Rozwiązało to mój problem","solvedMyProblem","thumb-up"],["Inne","otherUp","thumb-up"]],[["Brak potrzebnych mi informacji","missingTheInformationINeed","thumb-down"],["Zbyt skomplikowane / zbyt wiele czynności do wykonania","tooComplicatedTooManySteps","thumb-down"],["Nieaktualne treści","outOfDate","thumb-down"],["Problem z tłumaczeniem","translationIssue","thumb-down"],["Problem z przykładami/kodem","samplesCodeIssue","thumb-down"],["Inne","otherDown","thumb-down"]],["Ostatnia aktualizacja: 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)."]]