Help us understand the problem. What is going on with this article?

SwiftalyticsでAOPなGoogle Analyticsのスクリーントラッキングを行う

More than 3 years have passed since last update.

何ができるのか?

Swiftalyticsというライブラリを使い、Google Analyticsのスクリーントラッキングをファイル1つで管理できるようにします。
ViewControllerには手を触れずにトラッキングできるのが良さげです。

環境

  • Xcode 7.2.1
  • OS X 10.11.3

手順

SwiftalyticsとGoogle Analytics設定

XcodeのProjectに下記のPodfileを追加します。

Podfile
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'

use_frameworks!

pod 'Swiftalytics', '~> 0.2'
pod 'GoogleAnalytics'

pod setupでライブラリをインストールします。

$pod setup

次にBridge-Header.hにGoogleAnalyticsのヘッダを追加します。

Bridge-Header.h
#import <GoogleAnalytics/GAI.h>
#import <GoogleAnalytics/GAIFields.h>
#import <GoogleAnalytics/GAILogger.h>
#import <GoogleAnalytics/GAIDictionaryBuilder.h>

Swiftalytics用のクラスを作成します。

Swiftalyticsサンプルを参考にしながら下記のようなクラスを追加します。

ポイントはMethodSwizzlingを利用してswiftalytics_viewDidAppearviewDidAppearの順に処理が呼ばれるようになっているところでしょうか。
これにより、UIViewControllerの実装には手を加えずにviewDidAppearの直前にswiftalytics_viewDidAppearを差し込むことができるようになります。

ScreenTracking.swift
import UIKit
import Swiftalytics

struct ScreenTracking {
    static func setup() {
        FirstViewController.self >> "First Screen"
        SecondViewController.self >> "Second Screen"
    }
}

extension UIViewController {
    public override class func initialize() {
        struct Static {
            static var token: dispatch_once_t = 0
        }

        // make sure this isn't a subclass
        if self !== UIViewController.self {
            return
        }

        dispatch_once(&Static.token) {
            let originalSelector = Selector("viewDidAppear:")
            let swizzledSelector = Selector("swiftalytics_viewDidAppear:")

            let originalMethod = class_getInstanceMethod(self, originalSelector)
            let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)

            let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))

            if didAddMethod {
                class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
            } else {
                method_exchangeImplementations(originalMethod, swizzledMethod)
            }
        }
    }

    func swiftalytics_viewDidAppear(animated: Bool) {
        swiftalytics_viewDidAppear(animated)
        if let name = Swiftalytics.trackingNameForViewController(self) {
            print("\(name)")
            let tracker = GAI.sharedInstance().defaultTracker
            tracker.set(kGAIScreenName, value: name)
            let builder = GAIDictionaryBuilder.createScreenView()
            tracker.send(builder.build() as [NSObject: AnyObject])
        }
    }
}

postfix operator << {}
private postfix func << <T: UIViewController>(trackClassFunction: (T -> () -> String)) {
   Swiftalytics.setTrackingNameForViewController(trackClassFunction)
}

private func >> <T: UIViewController>(left: T.Type, @autoclosure right: () -> String) {
    Swiftalytics.setTrackingNameForViewController(left, name: right)
}

private func >> <T: UIViewController>(left: T.Type, right: TrackingNameType) {
    Swiftalytics.setTrackingNameForViewController(left, trackingType: right)
}

private func >> <T: UIViewController>(left: T.Type, right: (T -> String)) {
    Swiftalytics.setTrackingNameForViewController(left, nameFunction: right)
}

didFinishLaunchingWithOptionsを編集

AppDelegate.swiftのdidFinishLaunchingWithOptionsに先ほど作成したScreenTrackingのsetup()とGoogleAnalyticsの設定を追加します。

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

        // Configure tracker from GoogleService-Info.plist.
        let gai = GAI.sharedInstance()
        gai.trackUncaughtExceptions = true
        gai.dispatchInterval = 20
        gai.logger.logLevel = .Verbose
        gai.trackerWithTrackingId("GA-xxxxxx") // 適宜変更してください

        return true
    }

実行すると、画面が切り替わるたびにswiftalytics_viewDidAppearが呼ばれ、トラッキングの処理が実行されると思います。

サンプルプロジェクト

サンプルコードを用意しました。
https://github.com/takezou621/SwiftalyticsGASample

bengo4
「専門家をもっと身近に」を理念として、人々と専門家をつなぐポータルサイト「弁護士ドットコム」「弁護士ドットコムニュース」「税理士ドットコム」を提供。
https://corporate.bengo4.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした