Panduan Memulai iOS

Langkah-langkah yang dijelaskan di halaman ini menjelaskan cara cepat membuat aplikasi iOS sederhana yang membuat permintaan ke YouTube Data API. Contoh ini menunjukkan cara mengambil data tentang channel YouTube GoogleDevelopers. Kode tersebut juga menyertakan komentar yang menjelaskan cara memodifikasi kueri untuk mengambil data tentang channel YouTube pengguna saat ini.

Prasyarat

Untuk menjalankan panduan memulai ini, Anda memerlukan:

  • Xcode 8.0 atau yang lebih baru.
  • Pengelola dependensi CocoaPods.
  • Akses ke internet dan browser web.
  • Akun Google.

Langkah 1: Aktifkan YouTube Data API

  1. Gunakan wizard ini untuk membuat atau memilih project di Google Developers Console, dan otomatis mengaktifkan API. Klik Continue, lalu Go to credentials.

  2. Di halaman Create credentials, klik tombol Cancel.

  3. Di bagian atas halaman, pilih tab Layar persetujuan OAuth. Pilih Alamat email, masukkan Nama produk jika belum ditetapkan, dan klik tombol Simpan.

  4. Pilih tab Credentials, klik tombol Create credentials, lalu pilih OAuth client ID.

  5. Pilih jenis aplikasi iOS, masukkan nama "YouTube Data API Quickstart", paket ID com.example.QuickstartApp, dan klik tombol Create.

Langkah 2: Siapkan ruang kerja

  1. Buka Xcode dan buat project baru:
    1. Klik File > New > Project, pilih template iOS > Application > Single View Application, lalu klik Next.
    2. Tetapkan Product Name ke "QuickstartApp", Organization Identifier menjadi "com.example", dan Language ke Objective-C. Di bawah ID organisasi, Anda akan melihat ID Paket yang dihasilkan dan cocok dengan ID Paket iOS (com.example.QuickstartApp) yang Anda masukkan pada langkah 1.b.
    3. Klik Berikutnya.
    4. Pilih direktori tujuan untuk project tersebut dan klik Create.
  2. Tutup project dengan mengklik File > Close Project.
  3. Buka jendela Terminal dan pilih direktori yang berisi file QuickstartApp.xcodeproj yang baru saja Anda buat.
  4. Jalankan perintah berikut untuk membuat Podfile, menginstal library, dan membuka project Xcode yang dihasilkan:

    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. Di XCode Project Navigator, pilih node project "QuickstartApp". Kemudian, klik item menu File > Tambahkan file ke "QuickstartApp".

  6. Temukan file GoogleService-Info.plist yang didownload sebelumnya, lalu pilih file tersebut. Klik tombol Options.

  7. Buat pilihan berikut di jendela opsi, lalu klik tombol Add:

    1. Centang kotak Salin item jika perlu.
    2. Centang semua target yang tercantum di bagian Tambahkan ke target.

  8. Dengan node project yang masih dipilih, pilih "QuickstartApp" di bagian TARGETS seperti yang ditampilkan pada dua gambar di bawah:

    1. Klik area yang ditampilkan dalam screenshot ini:

    2. Lalu pilih target yang tepat:

  9. Pilih tab Info, lalu luaskan bagian URL Types.

  10. Klik tombol +, lalu tambahkan skema URL untuk client ID terbalik Anda. Untuk menemukan nilai ini, buka file konfigurasi GoogleService-Info.plist yang Anda pilih pada langkah 2.f. Cari kunci REVERSED_CLIENT_ID. Salin nilai kunci tersebut, lalu tempelkan ke kotak Skema URL di halaman konfigurasi. Biarkan kolom lainnya kosong.

  11. Build ulang project:

    1. Klik Product > Clean Build Folder (sambil menahan tombol option).
    2. Klik Product > Build.

Langkah 3: Siapkan contoh aplikasi

Ganti konten file berikut dengan kode yang diberikan:

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

Langkah 4: Jalankan contoh aplikasi

Beralihlah ke skema QuickstartApp dengan mengklik Product > Scheme > QuickstartApp, lalu jalankan contoh (Cmd+R) menggunakan Simulator Perangkat atau perangkat yang dikonfigurasi. Saat pertama kali menjalankan contoh, Anda akan diminta untuk login ke Akun Google Anda dan mengizinkan akses.

Catatan

  • Informasi otorisasi disimpan di Keychain, sehingga eksekusi berikutnya tidak akan meminta otorisasi.

Bacaan lebih lanjut