๐ 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โฆ
๐ 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
I integrated amplitude analytics to my app โDevMindโ so I will share about this process step by step step
๐ง Step 1: Install Amplitude SDK
First, add the AmplitudeSwift SDK to your project. You can use Swift Package Manager (SPM):
- In Xcode, go to File > Add Packages.
- Enter the AmplitudeSwift GitHub URL:
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