30
31

More than 5 years have passed since last update.

SwiftのプロジェクトにGoogle Analytics SDKを導入する

Posted at

分析ツールですが、やはりGoogle Analyticsが導入コストも低く、いろんな角度で分析できるので無難かなと思ってます。
Swiftのプロジェクトに導入するまでの手順をまとめました。

Cocoapods

Podfile
pod 'GoogleAnalytics', '~> 3.13.0'

Bridging-Headerに記述

Example-Briding-Header.swift
...
#import "GAI.h"
#import "GAIFields.h"
#import "GAILogger.h"
#import "GAIDictionaryBuilder.h"
...

起動時のセットアップ

AppDelegate.swift
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        ...
        AppDelegate.setupGoogleAnalytics()
        ...
    }

    ...
    var tracker: GAITracker?
    class func setupGoogleAnalytics() {
        GAI.sharedInstance().trackUncaughtExceptions = true
        GAI.sharedInstance().dispatchInterval = 20
#if DEBUG
        GAI.sharedInstance().dryRun = true
        GAI.sharedInstance().logger.logLevel = .Info
#else
        GAI.sharedInstance().dryRun = false
        GAI.sharedInstance().logger.logLevel = .None
#endif
        if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
            appDelegate.tracker = GAI.sharedInstance().trackerWithTrackingId("UA-111111-1")
        }
    }
    ...

スクリーンをTrackする

各UIViewControllerのviewWillAppearにて。

  • screenName は設計によるので自由に設定する
  • もちろん全てのクラスに下記を書くのは冗長なのでHelperとかExtensionとかで一行のメソッドにするか、親クラスでこれをやって継承するなどお好みで
ExampleViewController.swift
override func viewWillAppear(animated: Bool) {
    if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
        let bundleName = NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String
        let className = NSStringFromClass(type).componentsSeparatedByString(".").last!
        let screenName = [bundleName, className].joinWithSeparator(".")
        let build = GAIDictionaryBuilder.createScreenView().set(screenName, forKey: kGAIScreenName).build() as NSDictionary
        appDelegate.tracker?.send(build as [NSObject : AnyObject])
        appDelegate.tracker?.set(kGAIScreenName, value: nil)
    }
}

イベントをTrackする

画面以外はイベントを設定するのが良いので、必要な箇所にて下記を記述する。

SomeEventClass.swift
    if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
        let build = GAIDictionaryBuilder.createEventWithCategory("category",action: "action",label: "label",value: 999).build() as [NSObject : AnyObject]
        appDelegate.tracker?.send(build)
    }
30
31
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
30
31