Incorpora videos de YouTube en aplicaciones de iOS con la biblioteca de ayuda de YouTube
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
youtube-ios-player-helper
es una biblioteca de código abierto que te ayuda a incorporar un reproductor de iframe de YouTube en una aplicación para iOS. La biblioteca crea un WebView
y un puente entre el código Objective-C de tu aplicación y el código JavaScript del reproductor de YouTube, lo que permite que la aplicación para iOS controle el reproductor de YouTube. En este artículo, se describen los pasos para instalar la biblioteca y comenzar a usarla desde tu aplicación para iOS.
Instalación
En este artículo, se da por sentado que creaste un nuevo proyecto de aplicación para iOS de vista única orientado a la versión más reciente de iOS y que agregas los siguientes archivos cuando creas el proyecto:
Main.storyboard
ViewController.h
ViewController.m
Puedes instalarla a través de CocoaPods o copiando los archivos fuente y la biblioteca de la página de GitHub del proyecto.
- La biblioteca está disponible para instalarla a través de CocoaPods. Como alternativa, la biblioteca y los archivos fuente están disponibles a través de la página de GitHub del proyecto y se pueden copiar en un proyecto existente.
Instala la biblioteca mediante CocoaPods
Si tu proyecto usa CocoaPods, agrega la siguiente línea a tu Podfile para instalar la biblioteca.
En esa línea, reemplaza x.y.z
por la versión más reciente del pod, que se identificará en la página de GitHub del proyecto.
pod "youtube-ios-player-helper", "~> x.y.z"
En la ventana de la línea de comandos, escribe pod install
para actualizar el lugar de trabajo con las dependencias.
Sugerencia: Recuerda que cuando uses CocoaPods, debes abrir el archivo .xcworkspace
en Xcode, no el archivo .xcodeproj
.
Consulta el instructivo de CocoaPods para obtener más información.
Cómo instalar la biblioteca de forma manual
Para instalar la biblioteca auxiliar de forma manual, descarga la fuente mediante el vínculo de descarga de GitHub o clona el repositorio. Una vez que tengas una copia local del código, sigue estos pasos:
Abre el proyecto de muestra en Xcode o Finder.
Selecciona YTPlayerView.h
, YTPlayerView.m
y la carpeta Assets. Si abres el lugar de trabajo en Xcode, puedes encontrar esta información en Pods -> Pods -> Pods -> YouTube-Player-iOS-Helper y Pods -> Pods -> YouTube-Player-iOS-Helper -> Resources. En Finder, estos están disponibles en el directorio raíz del proyecto, en los directorios Clases y Activos.
Arrastra los archivos y las carpetas al proyecto. Asegúrate de que la opción Copiar elementos a la carpeta del grupo de destino esté marcada. Cuando arrastres la carpeta Elementos, asegúrate de que esté marcada la opción Crear referencias de carpeta para cualquier carpeta agregada.
Se debería instalar la biblioteca.
Agrega un elemento YTPlayerView
a través de Interface Builder o del guion gráfico
Para agregar un YTPlayerView
mediante Interface Builder o el guion gráfico, sigue estos pasos:
-
Arrastra una instancia de UIView
a tu View.
-
Selecciona el Inspector de identidad y cambia la clase de la vista a YTPlayerView
.
-
Abre ViewController.h
y agrega el siguiente encabezado:
#import “YTPlayerView.h”
También agrega la siguiente propiedad:
@property(nonatomic, strong) IBOutlet YTPlayerView *playerView;
-
En Interface Builder, crea una conexión desde el elemento View que definiste en el paso anterior con la propiedad playerView
del controlador de vista.
-
Ahora, abre ViewController.m
y agrega el siguiente código al final de tu método viewDidLoad
:
[self.playerView loadWithVideoId:@"M7lc1UVf-VE"];
Compila y ejecuta tu aplicación. Cuando se cargue la miniatura del video, presiónala para iniciar el reproductor de video en pantalla completa.
Controlar la reproducción de video
El método ViewController::loadWithVideoId:
tiene una variante, loadWithVideoId:playerVars:
, que permite a los desarrolladores pasar variables de reproductor adicionales a la vista. Estas variables de reproductor corresponden a los parámetros del reproductor en la API del reproductor de IFrame. El parámetro playsinline
permite que el video se reproduzca directamente en la vista, en lugar de reproducirse en pantalla completa. Cuando se reproduce un video de forma intercalada, la app para iOS puede controlar la reproducción de manera programática.
Reemplaza la llamada loadWithVideoId:
por este código:
NSDictionary *playerVars = @{
@"playsinline" : @1,
};
[self.playerView loadWithVideoId:@"M7lc1UVf-VE" playerVars:playerVars];
Abre el guión gráfico o el Compilador de interfaces. Arrastra dos botones a tu vista, etiquétalos como Reproducir y Detener. Abre ViewController.h
y agrega estos métodos, que se asignarán a los botones:
- (IBAction)playVideo:(id)sender;
- (IBAction)stopVideo:(id)sender;
Ahora abre ViewController.m
y define estas dos funciones:
- (IBAction)playVideo:(id)sender {
[self.playerView playVideo];
}
- (IBAction)stopVideo:(id)sender {
[self.playerView stopVideo];
}
La mayoría de las funciones de la API del reproductor de IFrame tienen equivalentes de Objective-C, aunque algunos de los nombres pueden variar un poco para coincidir mejor con los lineamientos de codificación de Objective-C. Las excepciones notables son los métodos que controlan el volumen del video, ya que lo controla el hardware del teléfono o con instancias UIView
integradas diseñadas para este propósito, como MPVolumeView
.
Abre el guión gráfico o el Compilador de interfaces y mantén presionada la tecla Control y arrastra para conectar los botones Reproducir y Detener a los métodos playVideo:
y stopVideo:
.
Ahora, compila y ejecuta la aplicación. Una vez que se cargue la miniatura del video, podrás reproducir y detener el video con los controles nativos y los del reproductor.
Cómo controlar devoluciones de llamada del reproductor
Puede ser útil para controlar de manera programática los eventos de reproducción, como los cambios de estado de reproducción y los errores de reproducción. En la API de JavaScript, esto se hace con objetos de escucha de eventos.
En Objective-C,esto se hace con un delegado.
En el siguiente código, se muestra cómo actualizar la declaración de interfaz en ViewController.h
para que la clase se ajuste al protocolo de delegado. Cambia la declaración de la interfaz de ViewController.h
de la siguiente manera:
@interface ViewController : UIViewController<YTPlayerViewDelegate>
YTPlayerViewDelegate
es un protocolo para controlar eventos de reproducción en el reproductor.
Si quieres actualizar ViewController.m
para controlar algunos de los eventos, primero debes establecer la instancia ViewController
como el delegado de la instancia YTPlayerView
. Para realizar este cambio, agrega la siguiente línea al método viewDidLoad
en ViewController.h
.
self.playerView.delegate = self;
Ahora agrega el siguiente método a 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;
}
}
Compila y ejecuta la aplicación. Mira el resultado del registro en Xcode a medida que cambia el estado del reproductor.
Deberías ver las actualizaciones cuando se reproduzca o detenga el video.
La biblioteca proporciona las constantes que comienzan con el prefijo kYT*
para mayor comodidad y legibilidad. Para obtener una lista completa de estas constantes, consulta YTPlayerView.m
.
Prácticas recomendadas y limitaciones
La biblioteca se basa en la API del reproductor IFrame mediante la creación de un WebView
y el procesamiento de HTML y JavaScript necesarios para un reproductor básico. El objetivo de la biblioteca es que sea lo más fácil de usar posible y agrupar los métodos que los desarrolladores deben escribir con frecuencia en un paquete. Se deben tener en cuenta algunas limitaciones:
- La biblioteca no admite la reproducción simultánea de videos en varias instancias de
YTPlayerView
. Si tu aplicación tiene varias instancias de YTPlayerView
, se recomienda pausar o detener la reproducción en cualquier instancia existente antes de iniciarla en una instancia diferente. En la aplicación de ejemplo que se incluye en el proyecto, los ViewControllers usan NSNotificationCenter
para despachar notificaciones que la reproducción está a punto de comenzar. Se notifica a otros ViewControllers y pausarán la reproducción en sus instancias YTPlayerView
.
- Vuelve a usar las instancias de
YTPlayerView
cargadas existentes cuando sea posible. Cuando se debe cambiar un video en una vista, no crees una nueva instancia UIView
o YTPlayerView
, ni llames a loadVideoId:
ni a loadPlaylistId:
. En su lugar, usa la familia de funciones cueVideoById:startSeconds:
, que no vuelve a cargar WebView
. Hay una demora notable cuando se carga todo el reproductor IFrame.
- Este reproductor no puede reproducir videos privados, pero puede reproducir videos no listados. Debido a que esta biblioteca une el reproductor iframe existente, el comportamiento del reproductor debe ser casi idéntico al de un reproductor incorporado en una página web en un navegador para dispositivos móviles.
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
Última actualización: 2023-02-22 (UTC)
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Falta la información que necesito","missingTheInformationINeed","thumb-down"],["Muy complicado o demasiados pasos","tooComplicatedTooManySteps","thumb-down"],["Desactualizado","outOfDate","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Problema con las muestras o los códigos","samplesCodeIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 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)."]]