Guía de inicio rápido de iOS

En los pasos descritos en esta página, se explica cómo crear rápidamente una aplicación para iOS simple que realiza solicitudes a la API de datos de YouTube. 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 esta guía de inicio rápido, necesitarás lo siguiente:

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

Paso 1: Activa la API de datos de YouTube

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

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

  3. En la parte superior de la página, seleccione la pestaña OAuth consent screen. 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 "YouTube Data API Quickstart", agrupa el ID com.example.QuickstartApp y haz clic en el botón Crear.

Paso 2: Prepara el lugar de trabajo

  1. Abre Xcode y crea un proyecto nuevo:
    1. Haz clic en File > New > Project, selecciona la plantilla iOS > Application > Single View Application y haz clic en Next.
    2. Establece el Nombre del producto en "Guía de inicio rápido", el Identificador de la organización en "com.example" y el Idioma enObjective-C. Debajo del identificador de la organización, deberías ver un Identificador de paquete generado que coincide 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. Cierra el proyecto haciendo clic en File > Close Project.
  3. Abre una ventana de la 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 del proyecto de XCode, selecciona el nodo del proyecto "QuickstartApp". Luego, haz clic en el elemento de menú File > Add files to "QuickstartApp".

  6. Busca el archivo GoogleService-Info.plist descargado anteriormente y selecciónalo. Haga 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. Marque la casilla de verificación Copiar los elementos si es necesario.
    2. Marque todas las orientaciones que se enumeran en la sección Agregar a orientaciones.

  8. Con el nodo del proyecto seleccionado, selecciona "QuickstartApp" en la sección TARGETS, 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 tu 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 Esquemas de URL 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 Product > Build.

Paso 3: Configura la muestra

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 la muestra

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

Notas

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

Lecturas adicionales