I recently installed Firebase Analytics in my SwiftUI app. Everything works great except the automatic screen views. Am I obligated to call AnalyticsEventScreenView for every view I would like to track?
I recently installed Firebase Analytics in my SwiftUI app. Everything works great except the automatic screen views. Am I obligated to call AnalyticsEventScreenView for every view I would like to track?
Yes - due to the way SwiftUI views are structured, Analytics only sees NotifyingMulticolumnSplitViewController.
You'll have to send screen views manually (as stated in the docs), like this:
import SwiftUI
import Firebase
struct ContentView: View {
var body: some View {
NavigationView {
List {
NavigationLink(destination: OneView()) {
Text("One")
}
NavigationLink(destination: TwoView()) {
Text("Two")
}
}
.navigationTitle("Choose a screen")
.onAppear() {
Analytics.logEvent(AnalyticsEventScreenView,
parameters: [AnalyticsParameterScreenName: "\(ContentView.self)",
AnalyticsParameterScreenClass: "\(ContentView.self)"])
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import SwiftUI
import Firebase
struct OneView: View {
var body: some View {
Text("1")
.onAppear() {
Analytics.logEvent(AnalyticsEventScreenView,
parameters: [AnalyticsParameterScreenName: "\(OneView.self)",
AnalyticsParameterScreenClass: "\(OneView.self)"])
}
}
}
struct OneView_Previews: PreviewProvider {
static var previews: some View {
OneView()
}
}
Firebase 9.0.0 has introduced new APIs that are specific to SwiftUI and have exited beta. There is now a View extension that implements a ViewModifier that provides you some functionality:
func analyticsScreen(name: String,
class: String = "View",
extraParameters: [String: Any] = [:])
For example:
struct MyView: View {
var body: some View {
Text("Hey")
.analyticsScreen(
name: "Screen Name",
extraParameters: [
AnalyticsParameterScreenName: "\(type(of: self))",
AnalyticsParameterScreenClass: "\(type(of: self))"
]
)
}
}
Same Peter's answer but automatically generating the ids
import SwiftUI
import Firebase
struct OneView: View {
var body: some View {
Text("1")
.onAppear() {
Analytics.logEvent(AnalyticsEventScreenView,
parameters: [AnalyticsParameterScreenName: "\(type(of: self))",
AnalyticsParameterScreenClass: "\(type(of: self))"])
}
}
}
struct OneView_Previews: PreviewProvider {
static var previews: some View {
OneView()
}
}