iOS クイックスタート

このページで説明する手順では、YouTube Data API にリクエストを行うシンプルな iOS アプリケーションをすばやく作成する方法について説明します。このサンプルは、GoogleDevelopers YouTube チャンネルに関するデータを取得する方法を示しています。このコードには、現在のユーザーの YouTube チャンネルに関するデータを取得するようにクエリを変更する方法を説明するコメントも含まれています。

前提条件

このクイックスタートを実行するには、次のものが必要です。

  • Xcode 8.0 以降。
  • CocoaPods 依存関係マネージャー。
  • インターネット アクセスとウェブブラウザ。
  • Google アカウント。

ステップ 1: YouTube Data API を有効にする

  1. Google Developers Console でこのウィザードを使ってプロジェクトを作成するか既存のプロジェクトを選択すると、自動的に API が有効になります。[続行]、[認証情報に進む] の順にクリックします。

  2. [認証情報を作成] ページで、[キャンセル] ボタンをクリックします。

  3. ページ上部の [OAuth 同意画面] タブを選択します。[メールアドレス] を選択し、[ユーザーに表示するサービス名] が設定されていない場合はサービス名を入力して、[保存] ボタンをクリックします。

  4. [認証情報] タブを選択し、[認証情報を作成] ボタンをクリックして、[OAuth クライアント ID] を選択します。

  5. アプリケーションの種類として [iOS] を選択し、名前「YouTube Data API Quickstart」、バンドル ID com.example.QuickstartApp を入力して、[作成] ボタンをクリックします。

ステップ 2: ワークスペースを準備する

  1. Xcode を開いて、新しいプロジェクトを作成します。
    1. [File] > [New] > [Project] をクリックし、[iOS > Application > Single View Application] テンプレートを選択して、[Next] をクリックします。
    2. プロダクト名を「QuickstartApp」、組織 IDを「com.example」、言語Objective-Cに設定します。組織 ID の下に、ステップ 1.b で入力した iOS バンドル IDcom.example.QuickstartApp)と一致する バンドル ID が生成されているはずです。
    3. [次へ] をクリックします。
    4. プロジェクトの宛先ディレクトリを選択し、[作成] をクリックします。
  2. [File] > [Close Project] をクリックしてプロジェクトを閉じます。
  3. ターミナル ウィンドウを開き、作成した QuickstartApp.xcodeproj ファイルを含むディレクトリに移動します。
  4. 次のコマンドを実行して、Podfile を作成し、ライブラリをインストールして、結果の XCode プロジェクトを開きます。

    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. XCode プロジェクト ナビゲータで、プロジェクト ノード「QuickstartApp」を選択します。次に、メニュー項目 [File > Add files to "QuickstartApp"] をクリックします。

  6. 先ほどダウンロードした GoogleService-Info.plist ファイルを見つけて選択します。[オプション] ボタンをクリックします。

  7. オプション ウィンドウで次の選択を行い、[追加] ボタンをクリックします。

    1. [Copy items if needed] チェックボックスをオンにします。
    2. [ターゲットに追加] セクションに表示されているすべてのターゲットを確認します。

  8. プロジェクト ノードが選択された状態で、次の 2 つの図に示すように、[TARGETS] セクションで [QuickstartApp] を選択します。

    1. このスクリーンショットに示す領域をクリックします。

    2. 適切なターゲットを選択します。

  9. [Info] タブを選択し、[URL Types] セクションを展開します。

  10. [+] ボタンをクリックし、反転クライアント ID の URL スキームを追加します。この値を確認するには、ステップ 2.f で選択した GoogleService-Info.plist 構成ファイルを開きます。REVERSED_CLIENT_ID キーを探します。見つかったキーの値をコピーし、構成ページの [URL スキーム] ボックスに貼り付けます。その他の入力欄は空白にしておきます。

  11. プロジェクトを再ビルドします。

    1. option キーを押しながら、[Product] > [Clean Build Folder] をクリックします。
    2. [Product] > [Build] をクリックします。

ステップ 3: サンプルを設定する

次のファイルの内容を、提供されたコードで置き換えます。

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

ステップ 4: サンプルを実行する

[Product > Scheme > QuickstartApp] をクリックして QuickstartApp スキームに切り替え、デバイス シミュレータまたは構成済みのデバイスを使用してサンプル(Cmd+R)を実行します。サンプルを初めて実行すると、Google アカウントにログインしてアクセスを承認するよう求められます。

メモ

  • 認証情報はキーチェーンに保存されるため、以降の実行では認証を求められません。

関連情報