3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

swift, iOSにおけるMixpanelを使ったイベントトラッキング管理の例

Last updated at Posted at 2018-04-29

iOSでイベントトラッキングを管理する時に作ったクラスの例を紹介します。

Mixpanelを使った例ですが、他の例でも簡単に応用できると思います。

EventのProtocolを作る

import Mixpanel

protocol Event {
    var eventName: String { get }
    var properties: [String: Any] { get }
    func track()
    func timeEvent()
}

extension Event {
    
    func track() {
        Mixpanel.sharedInstance()?.track(eventName, properties: properties)
    }
    
    func timeEvent() {
        Mixpanel.sharedInstance()?.timeEvent(eventName)
    }
}

Eventに準拠した各カテゴリのログ送信クラスを作成

enum SignupEvent: Event {
    case signupButton
    case permitNotificationButton(granted: Bool)
    
    var eventName: String {
        switch self {
        case .signupButton:
            return "signup_btn"
        case .permitNotificationButton:
            return "signup_permit_notification_btn"
    }
    
    var properties: [String: Any] {
        switch self {
        case .permitNotificationButton(let granted),
            return ["granted": granted]
        default:
            return [:]
        }
    }
}

swiftのcaseはcamelCaseで書きたいし、logはsnake_caseで送りたいので、eventNameで変換してます。CodableのCodingKeysのイメージです。

また、enumの引数でproperties情報を渡すのも、必要なものだけに限定できるので、良いなと思っています。

使い方

SignupEvent.signupButton.track()
SignupEvent.permitNotificationButton(granted: true).track()

 所感

  • 呼び出す時に記述が直感的。
  • ViewControllerなどでStringを引数に書かなかったりするから安全。
  • イベントグループ(ファネル)ごとにまとめたりしとくと、探しやすいし、直しやすい
  • protocol Extensionによってimport Mixpanelをprotocolしかしないのも良い。他のライブラリに変える時に楽そう

ログ、イベントトラッキングで消耗しないために、保守性、可読性、拡張性の高いクラス管理をしたいものです。

参考

https://qiita.com/H_Crane/items/15b93a4403a10426627a#firebase-analitics (ほぼ同じです。参考にさせていただきました :bow: )

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?