In this post we'll create a small extension to track which screens are being viewed in a SwiftUI application.

Why Track Screen Views?

Tracking screen views is essential for understanding user behavior within your app. By knowing which screens are viewed most often, you can make informed decisions about where to focus your development efforts, improve user experience, and ultimately drive engagement.

TelemetryDeck Integration

For This example we'll use TelemetryDeck.
You can create a free account(referral) and get your API key from the dashboard.
p.s. if you use my referral code (0XL7FMWOV3LYPR61) we'll both get 100,000 extra signals every month 🙌

Why TelemetryDeck?

TelemetryDeck is a powerful tool for tracking user interactions in your app. It provides a privacy-first approach to analytics, ensuring that user data is anonymized.

Setting up TelemetryDeck

import SwiftUI
import TelemetryDeck

@main
struct YourAppNameApp: App {
    init() {
        let config = TelemetryDeck.Config(appID: "YOUR-APP-ID")
        TelemetryDeck.initialize(config: config)
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Use Case: Tracking Screen Views

To track screen views, we can create a custom ViewModifier that will automatically log the screen name whenever a view appears. Here's a simple implementation:

import SwiftUI
import TelemetryDeck

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
            .screenViewEvent()
    }
}

extension View {
    func screenViewEvent(
        _ screen: String = #file,
        extraParameters: [String: String]? = nil
    ) -> some View {
        self.onAppear {
            TelemetryDeck.signal(
                "open.\(screen)",
                parameters: extraParameters ?? [:]
            )
        }
    }
}

Wrap up

In this post, we've created a simple yet effective way to track screen views in a SwiftUI application using a custom ViewModifier. By integrating with TelemetryDeck, we can gain valuable insights into user behavior and make data-driven decisions to improve our app.

Resources:

Read more

Share


Share Bluesky Mastodon Twitter LinkedIn Facebook