LoginSignup
3
3

More than 5 years have passed since last update.

TreasureDataにiOSアプリからログを送れるようにする

Posted at

はじめに

業務でアプリからTDへログを送ることになりました。
TreasureDataのSDK導入リファレンスにはObjective-Cの実装例しかなく、swiftで実装したところ紹介されているメソッド名なども若干違っておりました。
なのでどなたかの役に立てばと残しておきます。

下準備

CocoaPodsを使いインストールしていきます。
CocoaPodsインストール未済の場合は以下のようにインストールが必要となります。

$ gem install cocoapods

プロジェクト直下のPodfileに下記を追記してください。

Podfile
pod 'TreasureData-iOS-SDK', '= 0.1.24'
$ pod install

実装編

まずはTreasureDataライブラリのインポートを行なってください。

AppDelegate.swift
import TreasureData_iOS_SDK

その後下記のタイミングでTreasureDataの初期化を行なってください。

AppDelegate.swift
 open func application(_ application: UIApplication,
                          didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let tdSettings = TreasureDataEventLogger.setting.self 
    // TDのエンドポイントを指定してください
    TreasureData.initializeApiEndpoint("https://in.treasuredata.com") 
    // APIkeyはこちらに指定してください。
    TreasureData.initialize(withApiKey: API_KEY)
    // 使用するDB名をいれてください
    TreasureData.sharedInstance()?.defaultDatabase = "hogehoge"
    //もしもデバッグ版だけログを出力したいときなどに使用してください
    if isDebug {
         TreasureData.enableLogging()
    }
    // デバイスごとにユニークIDを付与することもできます。disableにもできますのでお好みで使用してください。
    TreasureData.sharedInstance()?.enableAutoAppendUniqId() 

実際にイベントを飛ばす

イベント送信タイミングはイベントがおきた際にTDへ送るようにしました。
AndroidだとonStop時と書いてあったので若干モヤモヤしました。(詳しい方教えてください)

hoge.swift
    var event: Dictionary<String, String> = [:]
    event["name"] = "みかん"
    event["gender"] = "female"
    event["strength"] = "100"

    TreasureData.startSession()
    TreasureData.sharedInstance().addEvent(event, table: "character")
    TreasureData.endSession()
    TreasureData.sharedInstance()?.uploadEvents()

As long as startSession is called but endSession is not called, the session will continue. Also, if startSession is called again within 10 seconds of the last calling endSession(), then the session resumes, instead of a new session being created.

endSession()が呼ばれても10秒以内にstartSession()が呼び出された際にはSessionが引き続き再開するようです。

おわり

https://support.treasuredata.com/hc/en-us/articles/360000671667-iOS-SDK
initializeのメソッド名がドキュメント上だとinitializeWithApiKeyだったり、先にAndroid側を実装したのですがuploadEvents()のタイミングがiOSとAndroidで違ったり難しいなぁと感じました。

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