LoginSignup
10
10

More than 5 years have passed since last update.

TitaniumでGoogle Analytics

Posted at

Titanium-Google-Analyticsというモジュール(Titanium Moduleではなくjsファイルで配布されている)を動かしたてみたので、その履歴を残しておきます。上記モジュールのコードの中をみるとgoogleのsdkをtitaniumに移植(ラップするモジュールを作成した等)した訳ではなく、ピュアなjavascriptで実装(渡されたパラメータを元にhttpリクエストを作成して送信しているだけ)しているようです。

サンプルコードを動かすまで

  1. Google Analyticsでウェブサイト用(モバイルではない)のトラッキングIDを作る

モバイルアプリをウェブサイト(ダミーの)に見立ててgoogle analyticsを使っているため
2. サンプルコードを動かす為の適当なプロジェクトを作成
3. [1] からコードをチェックアウト
4. Ti.Google.Analytics.jsを自分のプロジェクトにコピー
5. app.jsに以下のコードを追加

  var gaModule = require('Ti.Google.Analytics');
  var analytics = new gaModule("UA-XXXXXXXX"); //トラッキングID入

  Titanium.App.addEventListener('analytics_trackPageview', function(e){
      var path = "/app/" + Titanium.Platform.name;
      analytics.trackPageview(path + e.pageUrl);
  });
  Titanium.App.addEventListener('analytics_trackEvent', function(e){
      analytics.trackEvent(e.category, e.action, e.label, e.value);
  });
  Titanium.App.Analytics = {
      trackPageview:function(pageUrl){
          Titanium.App.fireEvent('analytics_trackPageview', {pageUrl:pageUrl});
      },
      trackEvent:function(category, action, label, value){
          Titanium.App.fireEvent('analytics_trackEvent', {category:category, action:action, label:label, value:value});
      }
  };
  analytics.start(10);

ほとんど参考URL[2]のサンプルコードですが、動かす為に以下の部分を変更する必要がありました。
- モジュールの読み込みをincludeからrequireへ変更
- 読み込むモジュール名をanalytics.jsからTi.Google.Analyticsへ変更
6. デフォルトで作成されているFirstView.jsとかに以下のコードを突っ込む

FirstView.js
    //label using localization-ready strings from <app dir>/i18n/en/strings.xml
    var label = Ti.UI.createLabel({
        color:'#000000',
        text:String.format(L('welcome'),'Titanium'),
        height:'auto',
        width:'auto'
    });
    self.add(label);

    //Add behavior for UI
    label.addEventListener('click', function(e) {
        alert(e.source.text);
        Titanium.App.Analytics.trackEvent('Button','click','hello world',1); //追加部分
    });

  Titanium.App.Analytics.trackPageview('/FirstView'); //追加部分

参考URL

[1] Example Titanium project that uses Google Analytics to track page views
https://github.com/rogchap/Titanium-Google-Analytics

[2] [Titanium Mobile] アプリ内の画面ページビューやボタンのクリック回数をGoogle Analyticsで計測する
http://m.designbits.jp/12111909/

10
10
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
10
10