iOS クイックスタート

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

Prerequisites

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

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

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

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

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

  3. ページ上部の [OAuth 同意画面] タブを選択します。[メールアドレス] を選択し、まだ設定していない場合はプロダクト名を入力して、[保存] ボタンをクリックします。

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

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

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

  1. Xcode を開き、新しいプロジェクトを作成します。
    1. [File] > [New] > [Project] をクリックし、[iOS] > [Application] > [Single View Application] テンプレートを選択し、[Next] をクリックします。
    2. [Product Name] を「クイックスタート アプリ」に、[Organization Identifier] を「com.example」に、[Language] を[Objective-C]に設定します。組織 ID の下に、ステップ 1.b で入力した iOS バンドル IDcom.example.QuickstartApp)と一致するバンドル ID が表示されます。
    3. [次へ] をクリックします。
    4. プロジェクトのインストール先ディレクトリを選択し、[Create] をクリックします。
  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. オプション ウィンドウで次のように選択し、[Add] ボタンをクリックします。

    1. [必要に応じてアイテムをコピー] チェックボックスをオンにします。
    2. [ターゲットに追加] セクションに表示されているすべてのターゲットを確認します。

  8. プロジェクト ノードを選択した状態で、次の 2 つの画像に示すように、[TARGETS] セクションで「quickstartApp」を選択します。

    1. 以下のスクリーンショットに示されている領域をクリックします。

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

  9. [情報] タブを選択し、[URL タイプ] セクションを開きます。

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

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

    1. [Product] > [Clean Build Folder]option キーを長押ししたまま)をクリックします。
    2. [Product] > [Build] をクリックします。

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

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

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

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;


@end
#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
#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
#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] をクリックし、デバイス シミュレータまたは構成済みデバイスを使用してサンプル(Cmd+R)を実行して、quickstartApp スキームに切り替えます。サンプルを初めて実行するときに、Google アカウントにログインしてアクセスを承認するように求められます。

備考

  • 承認情報はキーチェーンに保存されるため、後続の実行で承認を求められることはありません。

参考資料