Skip to content
DeveloperMemos

Simplifying Screen Tracking with the .analyticsScreen Modifier in SwiftUI

SwiftUI, FirebaseAnalytics, iOS1 min read

Firebase Analytics is a powerful tool for understanding user behavior within your iOS app. Tracking which screens users visit is a fundamental aspect of this analysis. While traditional methods involve manual logging within view controllers, SwiftUI offers a more concise approach using the .analyticsScreen modifier.

What is the .analyticsScreen modifier?

Introduced in SwiftUI versions following Xcode 13.2, the .analyticsScreen modifier provides a declarative way to track screen views within your SwiftUI application. This modifier lives within the FirebaseAnalyticsSwift framework and simplifies the process of logging screen names for analytics.

Using the .analyticsScreen modifier

Here's how to leverage the .analyticsScreen modifier in your SwiftUI views:

1struct MyContentView: View {
2
3 var body: some View {
4 VStack {
5 Text("Welcome to the App!")
6 Button("Next Screen") {
7 // ... navigate to next screen
8 }
9 }
10 .analyticsScreen(name: "Home") // Track this view as "Home" screen
11 }
12}

In this example, the .analyticsScreen modifier is applied to the entire VStack. This ensures that whenever this view appears on the screen, Firebase Analytics will log a screen view event with the name "Home."

Key points to remember:

  • The name parameter is mandatory and specifies the name you want to associate with the screen in your Firebase Analytics reports.
  • You can optionally provide an additional parameter class to specify the view controller class associated with the screen (defaults to "View").
  • The modifier can be applied to any view or view container within your SwiftUI hierarchy.

Wrapping Up

The .analyticsScreen modifier offers a convenient and SwiftUI-friendly way to track screen views in your iOS app. By incorporating this modifier into your views, you can gain valuable insights into user behavior and optimize your app for better engagement.