![Screen Shot 2014-05-18 at 8.02.27 AM.png](https://qiita-image-store.s3.amazonaws.com/0/40146/715444c8-6a6b-e96e-7e09-fe5aeba3cbb8.png "Screen Shot 2014-05-18 at 8.02.27 AM.png" "iOSでこれを取得してみる")
Objective-Cで、Googe Analytics Real Time Reporting APIを使って、現在のアクティブユーザー数を取得してみます。
Google Developer Consoleに登録
Google Developer Consoleで、APIの有効化とアプリケーション情報を登録する。
- 「API Project」(これはデフォルトのプロジェクト、別に新規にプロジェクトを作ってもOK)→「APIs & Auth」→「APIs」→「Analytics API」のSTATUSを「ON」に。
- 「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
//
#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のフォーラムより)
##参考文献