Analytics
Spring 2024 | Vin Bui
Last updated
Was this helpful?
Spring 2024 | Vin Bui
Last updated
Was this helpful?
Google Analytics is an app measurement solution that allows us to view our appβs usage and other insights. It allows us to understand how people use our applications through defining and tracking custom user events. It helps us understand the behavior of our users, allowing us to make informed product decisions and improving the user experience.
In order to set up Google Analytics, we must have a Firebase project configured for our app.
Under Project Settings > General, download the GoogleService-Info.plist
file and drag it into your project directory.
Install the Firebase SDK via CocoaPods or Swift Package Manager and choose the libraries that you want to use (in this case FirebaseAnalytics).
Follow the instructions from the to add the initialization code.
The does a pretty good job explaining how to set up Google Analytics so I wonβt repeat it here. Follow the guide to add the SDK.
Our first step is to create a file that will manage our analytics. Letβs call this file AnalyticsManager.swift
.
We can create custom events that can be triggered as a response to user interactions.
This is a general Event
type that will be used by Analytics to log. Letβs make it more specific to our app. Letβs use Uplift in our example.
Create an enum called UpliftEvent
with a raw String
type.
Define custom events with a case
statement. The raw value should be separated by underscores. In this example, we created an event that tracks the tapping of a gym cell.
Create a nested enum called EventType
. This enum will be used if we need to pass in parameters along with our events.
In the event we defined above, since we are tracking a userβs interaction with a gym cell, it would be useful to know which gym they are selecting. We can pass in parameters that will contain this information (which is why we create a gym
case in our EventType
enum).
Create a function that converts our UpliftEvent
to the Event
struct that we created earlier.
We handle the case in which there are no parameters using a guard let
statement and return just the raw value of the enum.
If there are parameters, we can perform a switch
statement to break down the event types to determine the key-value pair for the event parameters.
After defining all of our event types, we can then begin writing the actual AnalyticsManager
.
Just like any other utils manager we create (such as NetworkManager
), we create a shared singleton instance and make the initializer private.
We then create a single function that takes in an Event
type.
The #if DEBUG
statement is used to determine our appβs build setting. When working in a development environment, we do not want to be tracking analytics. Instead, we can print (or even better, log) the event in the development environment.
In our example, we can log the tapping of a gym cell with the following code: