Guía de inicio rápido para iOS

En los pasos que se describen en esta página, se explica cómo crear rápidamente una aplicación simple para iOS que realiza solicitudes a la API de YouTube Data. En este ejemplo, se muestra cómo recuperar datos sobre el canal de YouTube GoogleDevelopers. El código también incluye comentarios que explican cómo modificar la consulta para recuperar datos sobre el canal de YouTube del usuario actual.

Requisitos previos

Para ejecutar este inicio rápido, necesitarás lo siguiente:

  • Xcode 8.0 o una versión posterior
  • Administrador de dependencias de CocoaPods
  • Acceso a Internet y un navegador web
  • Una Cuenta de Google

Paso 1: Activa la API de YouTube Data

  1. Usa este asistente para crear o seleccionar un proyecto en la Consola de Google Developers y activar automáticamente la API. Haz clic en Continuar y, luego, en Ir a las credenciales.

  2. En la página Crear credenciales, haz clic en el botón Cancelar.

  3. En la parte superior de la página, selecciona la pestaña pantalla de consentimiento de OAuth. Selecciona una Dirección de correo electrónico, ingresa un Nombre del producto si aún no está configurado y haz clic en el botón Guardar.

  4. Selecciona la pestaña Credenciales, haz clic en el botón Crear credenciales y selecciona ID de cliente de OAuth.

  5. Selecciona el tipo de aplicación iOS, ingresa el nombre "API de YouTube Data Quickstart", el ID del paquete com.example.QuickstartApp y haz clic en el botón Crear.

Paso 2: Prepara el espacio de trabajo

  1. Abre Xcode y crea un proyecto nuevo:
    1. Haz clic en Archivo > Nuevo > Proyecto , selecciona la plantilla iOS > Aplicación > Aplicación de vista única y haz clic en Siguiente.
    2. Establece el Nombre del producto como "QuickstartApp", el Identificador de la organización como "com.example" y el Idioma como Objective-C. Debajo del identificador de la organización, deberías ver un Identificador del paquete generado que coincida con el ID del paquete de iOS (com.example.QuickstartApp) que ingresaste en el paso 1.b.
    3. Haz clic en Siguiente.
    4. Selecciona un directorio de destino para el proyecto y haz clic en Crear.
  2. Para cerrar el proyecto, haz clic en Archivo > Cerrar proyecto.
  3. Abre una ventana de terminal y navega al directorio que contiene el archivo QuickstartApp.xcodeproj que acabas de crear.
  4. Ejecuta los siguientes comandos para crear el Podfile, instalar la biblioteca y abrir el proyecto de XCode resultante:

    cat << EOF > Podfile &&
    platform :ios, '8.0'
    target 'QuickstartApp' do
        pod 'GoogleAPIClientForREST/YouTube', '~> 1.2.1'
        pod 'Google/SignIn', '~> 3.0.3'
    end
    EOF
    pod install &&
    open QuickstartApp.xcworkspace
    
  5. En el Navegador de proyectos de XCode, selecciona el nodo del proyecto "QuickstartApp". Luego, haz clic en el elemento de menú Archivo > Agregar archivos a "QuickstartApp".

  6. Busca el archivo GoogleService-Info.plist que descargaste antes y selecciónalo. Haz clic en el botón Opciones.

  7. Realiza las siguientes selecciones en la ventana de opciones y, luego, haz clic en el botón Agregar:

    1. Marca la casilla de verificación Copiar elementos si es necesario.
    2. Verifica todos los destinos que aparecen en la sección Agregar a destinos.

  8. Con el nodo del proyecto aún seleccionado, selecciona "QuickstartApp" en la sección DESTINOS , como se muestra en las dos imágenes siguientes:

    1. Haz clic en el área que se muestra en esta captura de pantalla:

    2. Luego, selecciona el destino adecuado:

  9. Selecciona la pestaña Información y expande la sección Tipos de URL.

  10. Haz clic en el botón + y agrega un esquema de URL para el ID de cliente invertido. Para encontrar este valor, abre el archivo de configuración GoogleService-Info.plist que seleccionaste en el paso 2.f. Busca la clave REVERSED_CLIENT_ID. Copia el valor de esa clave y pégalo en el recuadro URL Schemes en la página de configuración. Deja los demás campos en blanco.

  11. Vuelve a compilar el proyecto:

    1. Haz clic en Product > Clean Build Folder (mientras mantienes presionada la tecla option ).
    2. Haz clic en Project > Build.

Paso 3: Configura el ejemplo

Reemplaza el contenido de los siguientes archivos por el código proporcionado:

AppDelegate.h
#import <UIKit/UIKit.h>
@import GoogleSignIn;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;


@end
AppDelegate.m
#import "AppDelegate.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Initialize Google sign-in.
    [GIDSignIn sharedInstance].clientID = @"<YOUR_CLIENT_ID>";

    return YES;
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    return [[GIDSignIn sharedInstance] handleURL:url
                               sourceApplication:sourceApplication
                                      annotation:annotation];
}


@end
ViewController.h
#import <UIKit/UIKit.h>
@import GoogleSignIn;
#import <GTLRYouTube.h>

@interface ViewController : UIViewController <GIDSignInDelegate, GIDSignInUIDelegate>

@property (nonatomic, strong) IBOutlet GIDSignInButton *signInButton;
@property (nonatomic, strong) UITextView *output;
@property (nonatomic, strong) GTLRYouTubeService *service;


@end
ViewController.m
#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Configure Google Sign-in.
    GIDSignIn* signIn = [GIDSignIn sharedInstance];
    signIn.delegate = self;
    signIn.uiDelegate = self;
    signIn.scopes = [NSArray arrayWithObjects:kGTLRAuthScopeYouTubeReadonly, nil];
    [signIn signInSilently];

    // Add the sign-in button.
    self.signInButton = [[GIDSignInButton alloc] init];
    [self.view addSubview:self.signInButton];

    // Create a UITextView to display output.
    self.output = [[UITextView alloc] initWithFrame:self.view.bounds];
    self.output.editable = false;
    self.output.contentInset = UIEdgeInsetsMake(20.0, 0.0, 20.0, 0.0);
    self.output.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.output.hidden = true;
    [self.view addSubview:self.output];

    // Initialize the service object.
    self.service = [[GTLRYouTubeService alloc] init];
}

- (void)signIn:(GIDSignIn *)signIn
didSignInForUser:(GIDGoogleUser *)user
     withError:(NSError *)error {
    if (error != nil) {
        [self showAlert:@"Authentication Error" message:error.localizedDescription];
        self.service.authorizer = nil;
    } else {
        self.signInButton.hidden = true;
        self.output.hidden = false;
        self.service.authorizer = user.authentication.fetcherAuthorizer;
        [self fetchChannelResource];
    }
}


// Construct a query and retrieve the channel resource for the GoogleDevelopers
// YouTube channel. Display the channel title, description, and view count.
- (void)fetchChannelResource {
    GTLRYouTubeQuery_ChannelsList *query =
    [GTLRYouTubeQuery_ChannelsList queryWithPart:@"snippet,statistics"];
  query.identifier = @"UC_x5XG1OV2P6uZZ5FSM9Ttw";
  // To retrieve data for the current user's channel, comment out the previous
  // line (query.identifier ...) and uncomment the next line (query.mine ...).
  // query.mine = true;

  [self.service executeQuery:query
                    delegate:self
           didFinishSelector:@selector(displayResultWithTicket:finishedWithObject:error:)];
}

// Process the response and display output
- (void)displayResultWithTicket:(GTLRServiceTicket *)ticket
             finishedWithObject:(GTLRYouTube_ChannelListResponse *)channels
                          error:(NSError *)error {
  if (error == nil) {
    NSMutableString *output = [[NSMutableString alloc] init];
    if (channels.items.count > 0) {
      [output appendString:@"Channel information:\n"];
      for (GTLRYouTube_Channel *channel in channels) {
        NSString *title = channel.snippet.title;
        NSString *description = channel.snippet.description;
        NSNumber *viewCount = channel.statistics.viewCount;
        [output appendFormat:@"Title: %@\nDescription: %@\nViewCount: %@\n", title, description, viewCount];
      }
    } else {
      [output appendString:@"Channel not found."];
    }
    self.output.text = output;
  } else {
    [self showAlert:@"Error" message:error.localizedDescription];
  }
}


// Helper for showing an alert
- (void)showAlert:(NSString *)title message:(NSString *)message {
    UIAlertController *alert =
    [UIAlertController alertControllerWithTitle:title
                                        message:message
                                 preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok =
    [UIAlertAction actionWithTitle:@"OK"
                             style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction * action)
     {
         [alert dismissViewControllerAnimated:YES completion:nil];
     }];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}


@end

Paso 4: Ejecuta el ejemplo

Para cambiar al esquema QuickstartApp , haz clic en Product > Scheme > QuickstartApp y ejecuta el ejemplo (Cmd+R) con el simulador de dispositivos o un dispositivo configurado. La primera vez que ejecutes el ejemplo, se te pedirá que accedas a tu Cuenta de Google y autorices el acceso.

Notas

  • La información de autorización se almacena en tu llavero, por lo que las ejecuciones posteriores no solicitarán autorización.

Lecturas adicionales