LoginSignup
14
13

More than 5 years have passed since last update.

[iOS] Google Analytics Real Time Reporting APIを使って現在のアクティブユーザー数を取得する

Last updated at Posted at 2014-05-18

Screen Shot 2014-05-18 at 8.02.27 AM.png

Objective-Cで、Googe Analytics Real Time Reporting APIを使って、現在のアクティブユーザー数を取得してみます。

Google Developer Consoleに登録

Google Developer Consoleで、APIの有効化とアプリケーション情報を登録する。

  1. 「API Project」(これはデフォルトのプロジェクト、別に新規にプロジェクトを作ってもOK)→「APIs & Auth」→「APIs」→「Analytics API」のSTATUSを「ON」に。
  2. 「APIs & Auth」→「Consent screen」からアプリケーション情報を登録

ホワイトリストへの登録

Google Analytics Real Time Reporting APIは、2014/5/18現在、まだβ版で利用にはホワイトリストへの登録が必要。

Real Time Reporting APIのドキュメントのページの上のほうにある「request access to the beta.」のリンクから申し込みます。

なお、申し込みには、APIの「Project Number」の情報が必要。これはさきほど登録したGoogle Developer Consoleの各プロジェクトの「Overview」画面のトップに表示されているので、そこから取得します。

必要なライブラリのインストール

Objective-CでGoogle Analytics Reporting APIにアクセスするには、「Google APIs Client Library for Objective-C」を使うことができます。CocoaPodsでさくっとインストール。OAuth 2.0認証をやってくれるgtm-oauth2も一緒にインストールされます。

Podfile:

pod "Google-API-Client"

インストール:

pod install

実装

以下、ボタンを押すと、Googleアカウントのログイン画面を表示し、ログインに成功したらアクティブユーザー数を取得し、NSLog()で出力するサンプルです。Viewには、ボタンをひとつ置いて、TouchイベントにloginButtonTouchを繋げてください。

また、(1) OAuthのClient IDとClient secret (2) 取得したいGoogle AnalyticsのプロファイルIDが必要です。(1)は、Google Developer Consoleの「APIs & Auth」→「Credentials」で作成。 (2)は、Google Analyticsの「アナリティクス設定」で取得したいプロファイルを選択し、「ビュー設定」から「ビュー ID」を取得してください。

ViewController.m
//
//  ViewController.m
//

#import "ViewController.h"
#import "GTLAnalytics.h"
#import "GTMOAuth2ViewControllerTouch.h"

@interface ViewController ()

@end

@implementation ViewController{}

// 設定
NSString * const kKeychainItemName   = @"RealtimeSample";
NSString * const kClientID           = @"xxxxxxxxxxxx.apps.googleusercontent.com"; // OAuthのClient ID
NSString * const kClientSecret       = @"xxxxxxxxxxxx"; // OAuthのClient Secret
NSString * const kViewId             = @"ga:xxxxxxxx"; // 取得したいプロファイルのビューID
NSString * const kScope              = @"https://www.googleapis.com/auth/analytics.readonly";

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// ログイン
- (IBAction)loginButtonTouch:(UIButton *)sender
{
    // ログイン画面を表示
    GTMOAuth2ViewControllerTouch * authView =
        [[GTMOAuth2ViewControllerTouch alloc] initWithScope:kScope
                clientID:kClientID
                clientSecret:kClientSecret
                keychainItemName:kKeychainItemName
                delegate:self
                finishedSelector:@selector(viewController:finishedWithAuth:error:)
         ];
    [self presentViewController:authView animated:YES completion:nil];
}


// ログイン完了
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController finishedWithAuth:(GTMOAuth2Authentication *)auth
                 error:(NSError *)error
{
    // ログイン画面を閉じる
    [viewController dismissViewControllerAnimated:TRUE completion:nil];

    if (error != nil) {
        NSLog(@"ログイン失敗");
    } else {
        // クエリーを送信
        GTLQueryAnalytics * query =
            [GTLQueryAnalytics queryForDataRealtimeGetWithIds:kViewId
                                                      metrics:@"ga:activeVisitors"];
        GTLServiceAnalytics * service = [[GTLServiceAnalytics alloc] init];
        service.authorizer = auth;
        [service executeQuery:query
            completionHandler:^(GTLServiceTicket *ticket,
            GTLAnalyticsRealtimeData * data, NSError *error) {
                // 結果データを処理
                NSArray  * row = data.rows[0]; // 0の時はnil
                NSString * count = row[0];

                // 結果を出力
                NSLog(@"Active Users: %@", count);
        }];
    }
}

@end

[メモ1]Google Developer Consoleでテスト

Google Developer Consoleでは、各APIに実際にパラメーターを渡してどういう結果が返ってくるのか試せるので便利。

[メモ2]リクエスト制限

リクエスト制限は、デフォルトだと以下の通り。但し、申請すれば増やせる模様。

  • アプリごとに50,000リクエスト/日
  • IPごとに10リクエスト/秒
  • Google Analyticsプロファイルごとに10,000リクエスト/日

(Configuration and Reporting API Limits and Quotasより)

  • 最低30秒各リクエストの間隔を空けることを推奨

(Google Real Time Reporting APIのフォーラムより)

参考文献

14
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
13