โ† Back to list

๐Ÿ“Š Mastering Analytics in SwiftUI: Integrating Amplitude the Right Way

Analytics is essential in any app that aims to improve user experience, optimize performance, and understand user behavior. In thisโ€ฆ

Mahmoud Ramadan ยท 2025-08-23 12:40 ยท 0 claps ยท 3.3 min read paywalled
#ios-app-development #amplitude-analytics #swift-programming #swiftui #indiedev
Open on Medium โ†—
Wiki topics: UX ยท UI/UX Design GRW ยท Growth & Analytics ๐Ÿ’ป ยท Programming ๐Ÿ“ฑ ยท Mobile Development

๐Ÿ“Š Mastering Analytics in SwiftUI: Integrating Amplitude the Right Way

Analytics is essential in any app that aims to improve user experience, optimize performance, and understand user behavior. In this article, weโ€™ll walk through how to integrate Amplitude Analytics into a SwiftUI app. Weโ€™ll also build a reusable AnalyticsService to track events like task creation, session tracking, subscriptions, and app lifecycle events.

Not A member? Read from here

https://ramadandev.medium.com/mastering-analytics-in-swiftui-integrating-amplitude-the-right-way-94f69a244a36?sk=86a66228e5cdb7421d829dc1f94add2c

I integrated amplitude analytics to my app โ€œDevMindโ€ so I will share about this process step by step step

[embed]โ€ŽDevMind: Focus Timer & Tasks โ€ŽStay focused and boost productivity with DevMind's powerful focus timer and task management system. FOCUS FEATURES โ€ฆapps.apple.com

๐Ÿ”ง Step 1: Install Amplitude SDK

First, add the AmplitudeSwift SDK to your project. You can use Swift Package Manager (SPM):

  1. In Xcode, go to File > Add Packages.
  2. Enter the AmplitudeSwift GitHub URL:

[embed]GitHub - amplitude/Amplitude-Swift: Native iOS/tvOS/macOS/watchOS SDK Native iOS/tvOS/macOS/watchOS SDK. Contribute to amplitude/Amplitude-Swift development by creating an account onโ€ฆgithub.com

Choose the latest version and add it to your app target.

import AmplitudeSwift

๐Ÿ”ง Step 2: Create an Analytics Service

Instead of sprinkling analytics calls across your app, itโ€™s a best practice to create a dedicated service. Hereโ€™s the full implementation:

import Foundation
import AmplitudeSwift

// MARK: - Analytics Protocol
protocol AnalyticsServiceProtocol {
    func trackEvent(_ event: String, properties: [String: Any]? )
    func trackScreenView(_ screenName: String)
    func trackUserAction(_ action: String, context: String?)
    func trackError(_ error: Error, context: String?)
    func trackPerformance(_ metric: String, value: Double)
}

// MARK: - Analytics Service Implementation
@MainActor
class AnalyticsService: AnalyticsServiceProtocol {
    static let shared = AnalyticsService()

    private var isInitialized = false
    private var userUUID: String
    private var amplitude: Amplitude?

    private init() {
        // Generate anonymous user ID that persists across app launches
        if let existingUUID = UserDefaults.standard.string(forKey: "AnalyticsUserUUID") {
            self.userUUID = existingUUID
        } else {
            self.userUUID = UUID().uuidString
            UserDefaults.standard.set(self.userUUID, forKey: "AnalyticsUserUUID")
        }

        setupAnalytics()
    }

    private func setupAnalytics() {
        // Initialize Amplitude with your API key
        amplitude = Amplitude(configuration: Configuration(
            apiKey: AnalyticsConfig.amplitudeApiKey
        ))

        // Set user ID for tracking
        amplitude?.setUserId(userId: userUUID)

        isInitialized = true
        print("๐Ÿ“Š Analytics initialized with Amplitude - User ID: \(userUUID)")
    }

    // MARK: - Public Methods

    func trackEvent(_ event: String, properties: [String: Any]? = nil) {
        guard isInitialized else { return }

        var eventProperties = properties ?? [:]
        eventProperties["timestamp"] = Date().timeIntervalSince1970
        eventProperties["user_id"] = userUUID

        amplitude?.track(eventType: event, eventProperties: eventProperties)

        print("๐Ÿ“Š [ANALYTICS] Event: \(event), Properties: \(eventProperties)")
    }

    func trackScreenView(_ screenName: String) {
        trackEvent("screen_view", properties: [
            "screen_name": screenName,
            "screen_category": "navigation"
        ])
    }

    func trackUserAction(_ action: String, context: String? = nil) {
        var properties: [String: Any] = ["action_type": "user_interaction"]
        if let context = context {
            properties["context"] = context
        }
        trackEvent(action, properties: properties)
    }

    func trackError(_ error: Error, context: String? = nil) {
        var properties: [String: Any] = [
            "error_type": "app_error",
            "error_message": error.localizedDescription
        ]
        if let context = context {
            properties["context"] = context
        }
        trackEvent("error_occurred", properties: properties)
    }

    func trackPerformance(_ metric: String, value: Double) {
        trackEvent("performance_metric", properties: [
            "metric_name": metric,
            "metric_value": value,
            "metric_unit": "seconds"
        ])
    }

    // MARK: - Convenience Methods for Common Events

    func trackTaskCreated(title: String, estimatedMinutes: Int, category: String, priority: String) {
        trackEvent("task_created", properties: [
            "task_title": title,
            "estimated_minutes": estimatedMinutes,
            "category": category,
            "priority": priority
        ])
    }

    func trackTaskDeleted(title: String) {
        trackEvent("task_deleted", properties: [
            "task_title": title
        ])
    }

    func trackSessionStarted(taskTitle: String, estimatedMinutes: Int) {
        trackEvent("session_started", properties: [
            "task_title": taskTitle,
            "estimated_minutes": estimatedMinutes
        ])
    }

    func trackSessionCompleted(taskTitle: String, actualMinutes: Int, estimatedMinutes: Int, wasCompleted: Bool) {
        trackEvent("session_completed", properties: [
            "task_title": taskTitle,
            "actual_minutes": actualMinutes,
            "estimated_minutes": estimatedMinutes,
            "was_completed": wasCompleted
        ])
    }

    func trackAppLaunch() {
        trackEvent("app_launch", properties: [
            "launch_type": "cold_start"
        ])
    }

    func trackAppBackground() {
        trackEvent("app_background")
    }

    func trackAppForeground() {
        trackEvent("app_foreground")
    }

    func trackSubscriptionPurchased(type: String, price: Double, currency: String) {
        trackEvent("subscription_purchased", properties: [
            "subscription_type": type,
            "price": price,
            "currency": currency
        ])
    }

    func trackFeatureUsage(feature: String, context: String? = nil) {
        var properties: [String: Any] = ["feature_name": feature]
        if let context = context {
            properties["context"] = context
        }
        trackEvent("feature_used", properties: properties)
    }
}

๐Ÿ”ง Step 3: Define Event Names

To avoid typos and keep event naming consistent, create a central definition:

struct AnalyticsEvents {
    let subscriptionViewed = "subscription_viewed"
    let subscriptionPurchased = "subscription_purchased"
    let subscriptionRestored = "subscription_restored"

    let taskCreated = "task_created"
    let taskDeleted = "task_deleted"

    let sessionStarted = "session_started"
    let sessionCompleted = "session_completed"

    let appLaunch = "app_launch"
    let appBackground = "app_background"
    let appForeground = "app_foreground"

    let screenView = "screen_view"
    let errorOccurred = "error_occurred"
    let performanceMetric = "performance_metric"
    let featureUsed = "feature_used"
}

๐Ÿ”ง Step 4: Use Analytics in SwiftUI

Now you can track analytics events anywhere in your SwiftUI app.

Example: Tracking screen views in a ContentView:

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .onAppear {
                AnalyticsService.shared.trackScreenView("ContentView")
            }
    }
}
Button("Create Task") {
    AnalyticsService.shared.trackTaskCreated(
        title: "Study SwiftUI",
        estimatedMinutes: 60,
        category: "Learning",
        priority: "High"
    )
}

๐Ÿ“Š What We Achieved

  • Installed AmplitudeSwift using SPM.
  • Built a centralized AnalyticsService to send consistent events.
  • Defined event constants for safety.
  • Showed examples of tracking screens, actions, errors, performance, and subscriptions.

Before you go clapping and Follow me


๋ฉ”ํƒ€๋ฐ์ดํ„ฐ
post_id
94f69a244a36
slug
mastering-analytics-in-swiftui-integrating-amplitude-the-right-way-94f69a244a36
url
https://medium.com/@ramadandev/mastering-analytics-in-swiftui-integrating-amplitude-the-right-way-94f69a244a36
canonical_url
https://medium.com/@ramadandev/mastering-analytics-in-swiftui-integrating-amplitude-the-right-way-94f69a244a36
author_url
https://medium.com/@ramadandev
status
ok
fetched_at
2026-07-13 22:18:33