📦 SwiftyLaunch Modules
📈 AnalyticsKit
Overview

AnalyticsKit Module Overview

SwiftyLaunch Module - AnalyticsKit

Powered by PostHog

Powered by PostHog (Official Partner of SwiftyLaunch)

AnalyticsKit wraps PostHog's SDK to allow for an easy integration of analytics in your app.

After generating a project with AnalyticsKit enabled and completing the initial project setup, you will get following features out of the box:

  • Automatic Full SwiftyLaunch Modules Integration: All SwiftyLaunch Modules will take advantage of AnalyticsKit and capture events and errors without any additional setup or work from your end.
  • Ability to capture Events and Errors with a single line: Super-easy tracking. Read more.
  • Track what views the user opens: A view modifier that will capture whenever a view becomes active. Read more.
  • Session Recordings (BETA): Ability to record and watch complete user sessions. Read more.
  • Ability to track taps: A view modifier that will capture button or other view presses. Read more.
  • Automatic Crash detection and Reporting: Get full crash logs in case of an oopsie. Read more.
  • (AuthKit only) Ability to use a shared user ID: If the user is signed in, the Firebase user ID is used as the user ID in PostHog. Read more.
  • (BackendKit only) BackendKit integration: Almost complete feature parity of AnalyticsKit on the backend. Read more.

Module Deep Dive

Initialization and Configuration

Actions On App Launch

  1. We initilize AnalyticsKit in App.swift: by calling a static function Analytics.initPostHog()
  2. Only when generated with FirebaseKit (AuthKit + DBKit): We check if the app crashed during last execution, and if so, send the crash report to PostHog. Read more.
Analytics.initPostHog()

Here, we initialize PostHog with the API that you have placed in PostHog-Info.plist during project setup. We also set some additional configuration options, such as disabling automatic screen view tracking (as we track them ourselves) and enabling experimental session replays. The full list of configuration options can be found in the PostHog SDK documentation (opens in a new tab).

Analytics.swift
extension Analytics {
    static public func initPostHog() {
        do {
            let apiKey = try getPlistEntry("POSTHOG_API_KEY", in: "PostHog-Info")
            let host = try getPlistEntry("POSTHOG_HOST", in: "PostHog-Info")
            let config = PostHogConfig(apiKey: apiKey, host: host)
 
            // Doesn't work well with SwiftUI. We'll manually track screen views via the .captureViewActivity() Modifier
            config.captureScreenViews = false
 
            // EXPERIMENTAL SESSION REPLAYS:
            // https://posthog.com/docs/session-replay/mobile
            config.sessionReplay = true
            config.sessionReplayConfig.screenshotMode = true
            PostHogSDK.shared.setup(config)
        } catch {
            print("[ANALYTICS] PostHog Init Error: \(error.localizedDescription)")
            return
        }
    }
}

Actions when User signes in or out (only with FirebaseKit)

During app launch, we attach a a listener that listens to changes in the user's authentication state. When the user signs in, we call Analytics.associateUserWithID(USER_ID) to associate the user with the Firebase user ID. When the user signs out, we call Analytics.removeUserIDAssociation() to remove the association.

General Usage

The Analytics object and its functions are designed to be used as a static object throughout the application without having to store a persistant reference to it. That means you do not have to initialize it and simply call its functions by using Analytics.FUNCTION_NAME.

Capture an Event

The most common way to capture an event using AnalyticsKit would be by calling the static capture function.

Analytics.swift
public class Analytics {
    static public func capture(
        _ eventType: EventType,
        id: String,
        longDescription: String? = nil,
        source: EventSource,
        fromView: String? = nil,
        relevancy: EventRelevancy? = nil
    ) { }
}

This is how you call it:

import AnalyticsKit
 
func likePicture(withID pictureID: String) {
    // ... like the picture
    Analytics.capture(
        .success,
        id: "picture_liked",
        longDescription: "User liked picture with ID \(pictureID)",
        source: .general,
        fromView: "HomeFeedView"
    )
}

Read more about capturing events at Track Events and Errors.

AuthKit Integration

If AuthKit is selected during project generation, Analytics events will automatically be associated with the Firebase User ID in the PostHog Dashboard when the user is signed in. Otherwise a random anonymous ID will be used.

Module File Contents

Let's go through every file that is contained in the AnalyticsKit module:

Config

Contains the PostHog-Info.plist file that you will paste your PostHog API key into.

Sources

Model / Analytics.swift

Contains the Analytics class which is used to interact with the PostHog SDK and capture events.

ViewModifier / captureTaps.swift

Exposes the .captureTaps() view modifier that allows you to automatically capture taps on SwiftUI views. See Capture Taps for more information.

ViewModifier / captureViewActivity.swift

Exposes the .captureViewActivity() view modifier that allows you to automatically record when a SwiftUI view is shown on screen. See Capture View Activity for more information.