Firebase Analytics: Getting Started
Learn how Firebase Analytics can help you track iOS app usage. By Danijela Vrzan.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Firebase Analytics: Getting Started
25 mins
- Getting Started
- Setting Up Firebase
- Creating a Firebase Project
- Adding Firebase to Xcode
- Registering the App
- Downloading the Config File
- Adding Firebase SDK Using SwiftPM
- Initializing Firebase in Xcode
- Editing Build Settings
- Firebase Analytics Events
- Viewing Events in Dashboard
- Adding Predefined Events
- Adding Custom Events
- Enabling DebugView
- Viewing Events in DebugView
- Viewing Events in the Firebase Console
- User Properties and Audiences
- Filtering With User Properties
- Adding Custom User Properties
- Viewing User Properties in DebugView
- Adding User Properties in the Firebase Console
- Tailoring User Experiences with Audiences
- Where to Go From Here?
The day has finally come. Your Xcode project is building, and you’ve submitted your app to the App Store.
Now what? You brag on Twitter and beg your followers to install your app.
A few days later, you receive your first review. Someone named RayFromVA gave you a two-star review with a note: It could be better.
What does that mean?
You open your app. Everything works the way you intended. How do you know what could be better?
You could bribe your family to give you reviews, but Firebase Analytics offers a better solution.
In this Firebase Analytics tutorial, you’ll build Cocoabucks, a mobile storefront for a new coffee chain.
Along the way, you’ll learn how to:
- Set up Firebase SDK with SwiftUI using Swift Package Manager
- Log custom and predefined events
- Analyze user behavior with custom user properties
- Provide personalized user experiences using audiences
It’s worth noting that Google Analytics for Firebase has gone through many iterations over the years. Google renamed it Google Analytics in 2019, but everyone still calls it Firebase Analytics.
Getting Started
Download the starter project by clicking the Download Materials button at the top or bottom of the tutorial.
Open Cocoabucks.xcodeproj inside starter. Build and run to see the app in action:
In Xcode, take a look at the main files:
- products.json contains the app’s data.
- Cocoabucks.swift is the app’s entry point. All the life-cycle methods go here.
- ProductListView.swift is the app’s main view and displays a list of products. It has two buttons. One is for an analytics questionnaire you’ll use to assign custom user properties. The other is a cart button that leads to a checkout view.
- ProductDetailView.swift shows detailed information about a selected product. Add to cart adds the product to the cart.
-
CheckoutView.swift is a
Form
for displaying payment information and finalizing the order.
To use Firebase Analytics in your app, you first need to have a Firebase project set up.
Setting Up Firebase
Go to the Firebase homepage and click Get Started.
If you aren’t signed in with your Google account, enter your credentials. If you don’t have an account, create a new one.
You’ll then see a Firebase Console welcome screen:
Creating a Firebase Project
Creating a Firebase project is free. Click Create a project. A new window will appear:
Name your project Cocoabucks. Accept the Firebase terms and click Continue.
Firebase will ask you to add Google Analytics to your Firebase project.
Leave it enabled and click Continue.
The final step is setting your analytics location.
Setting a location doesn’t mean Google won’t track users from other countries. It only wants to know where your organization is or where you live, like it doesn’t know that already.
Accept the data-sharing terms and click Create project.
Click Continue, wait a bit, and you’ll see your project’s Console.
Adding Firebase to Xcode
Firebase Console is a container for your project’s Firebase services. You’ll use it to see your app’s analytics. Click the circle iOS button below Get started by adding Firebase to your app.
Registering the App
A new form will open asking you to register your app and enter your app’s bundle ID:
To set your app’s bundle ID, first head back to Xcode. Select Cocoabucks.xcodeproj. Then select your target and choose Signing & Capabilities.
Next, set your Apple Developer account under the Team drop-down menu. Finally, set the Bundle Identifier for your app following this format: com.[your name].cocoabucks. Be sure to fill in your name with all lowercase letters and no spaces.
Copy your bundle ID from Xcode. Go back to Firebase and paste it under iOS Bundle ID.
Click Register app.
Downloading the Config File
Next, download GoogleService-Info.plist. Drag it to your Xcode project by following the outlined instructions.
When prompted by Xcode, check Copy Items if needed.
Click Next and you’ll see a prompt to Add Firebase SDK to your Xcode.
Adding Firebase SDK Using SwiftPM
By default, Firebase tells you to add the SDK using CocoaPods:
In this tutorial, you’ll install Firebase SDK using SwiftPM.
Open Xcode and go to File ▸ Swift Packages ▸ Add Package Dependency:
A new window will open prompting you to enter the package repository URL. Copy and paste https://github.com/firebase/firebase-ios-sdk inside:
Click Next. You’ll see a new window asking you to choose package options:
Since these are the recommended options, leave everything as-is. Click Next.
Now, SwiftPM will fetch a list of all available libraries. Once it finishes, check FirebaseAnalytics:
Click Finish and SwiftPM will do everything for you. In the Document Outline, you’ll see it added Swift Package Dependencies to your project. Xcode might take a while to process everything:
Now go back to the Firebase Console and click Next.
Initializing Firebase in Xcode
To connect Firebase when your app starts, you need to initialize it inside your main class:
Firebase documentation doesn’t address SwiftUI or it’s new App life cycle yet. It has instructions for UIKit. You’ll learn how to do it in SwiftUI.
Go back to Xcode and open Cocoabucks.swift. Add the following to the top of the file:
import Firebase
Next, add the following below // Initialize Firebase
:
init() {
FirebaseApp.configure()
}
The code above starts the Firebase service once your app finishes launching.
Before you build your project, you need to add a few more things to avoid getting errors or warnings from Xcode.
Editing Build Settings
Click Cocoabucks in the Document Outline. Choose your target and, under Build Settings, find Other Linker Flags. Add -ObjC inside:
Build and run. Your app has been set up in the background and is already collecting some default analytics.
Go back to the Firebase console in your browser and click Next. Then click Continue to console. Now, you’ve added your iOS app to the Firebase project.
Firebase Analytics Events
You’ve gone through the process of creating a Firebase project and adding an iOS app to it. You haven’t added any code yet, but Firebase is already collecting some default analytics.
Like most of the other services, Firebase uses a system that’s built around events:
Every event has a name as a String
and an optional Dictionary
of parameters. Their values can be either a String
or an Int
.
When people use your app, the interaction fires off many events. They get tracked, coalesced and reported to you in the Firebase Console.
Firebase collects some basic interactions in any app by default:
- language the app is using
- app_exception if the app crashes
- app_update when the app updates to a new version
- first_open when the user launches the app for the first time
- screen_view when a screen transition occurs
You can find a full list of those events in the Firebase Documentation. You’ll need to log most other events yourself inside the app.
Viewing Events in Dashboard
Open the Firebase Console and go to Analytics ▸ Dashboard:
Instead, Firebase has a DebugView where you can see analytics collected in near real-time. You’ll see it in action in a few sections.
Check the Dashboard to see how different events are collected and presented. You can see how stable your app is or how many users you had in the last 30 minutes.
Adding Predefined Events
Firebase suggests you use predefined events in your app. The context behind them is already defined, and you can see some extra information.
You’re building an e-commerce app with a neat list of predefined events suitable for that type. You can find them in the Events: Retail/E-commerce list.
One of those events is purchases. You’ll add some of them to the checkout process.
Go back to Xcode and open CheckoutView.swift. Add the following to the top of the file:
import Firebase
You’ll add a predefined event for completing an order. A perfect time to log that event is when the user taps Confirm order.
Replace // TODO 1
inside the action of Confirm order with:
FirebaseAnalytics.Analytics.logEvent(AnalyticsEventPurchase, parameters: [
AnalyticsParameterPaymentType: Self.paymentTypes[paymentType],
AnalyticsParameterPrice: totalPrice,
AnalyticsParameterSuccess: "1",
AnalyticsParameterCurrency: "USD"
])
Firebase Analytics uses logEvent(_:parameters:)
to log all types of events.
In the code above, you log the predefined event named AnalyticsEventPurchase
. You add the predefined parameters named AnalyticsParameterPaymentType
, AnalyticsParameterPrice
and AnalyticsParameterCurrency
.
You assign them values of paymentType
and totalPrice
, based on user selection. The currency parameter has a single value so you give it a default value of USD.
When you start typing AnalyticsEvent
, Xcode will show you a list of all available options:
You can distinguish between events and parameters by looking at their prefixes. Events have the prefix AnalyticsEvent
, while parameters begin with AnalyticsParameter
.
Build and run. Add a few items to your cart. Then view your cart and select Place Order.
Finally, select Confirm Order. Firebase will log a purchase event every time a user confirms an order in your app.
Adding Custom Events
You can create custom events to analyze an event that isn’t already defined or change an existing one. Tracking screens is one of the most common events app developers track in their apps.
Firebase tracks a default event named AnalyticsEventScreenView, but assigns a generic class name to it.
Having NotifyingMulticolumnSplitViewController as a screen name doesn’t tell you much.
In this case, it’s a good idea to create a custom event.
In Xcode, open ProductDetailView.swift and add the following to the top of the file:
import Firebase
Next, replace // TODO 2
inside .onAppear()
with:
// 1
FirebaseAnalytics.Analytics.logEvent("detail_screen_viewed", parameters: [
// 2
AnalyticsParameterScreenName: "product_detail_view",
// 3
"product_name": product.name
])
Here’s a breakdown:
- You log both custom and predefined events with
logEvent(_:parameters:)
. The only difference is you choose whether you’re using a custom or a predefined name for it. So, you name it something descriptive like detail_screen_viewed. - There’s a predefined parameter,
AnalyticsParameterScreenName
, so you add it to the parametersDictionary
. - Finally, you add one custom parameter and name it product_name. Assign a current product’s name as a value to this parameter.
You can mix and match both custom and predefined events and parameters to your liking. Keep your event names short and distinctive since there’s a limit of 40 characters for event names.
Build and run. Firebase will now log your custom event every time the detailed view appears on the phone’s screen.
It’s time to see some analytics in action and what happens to your app in the background.
Enabling DebugView
As you develop apps, it’s helpful to see what’s happening in the background while you code. In this case, you want to see if events are being logged. Firebase has a tool for that called DebugView.
First, you need to enable it. In Xcode, go to Product ▸ Scheme ▸ Edit Scheme. Within the Run event, select Arguments.
In Arguments Passed On Launch, click + and enter -FIRAnalyticsDebugEnabled.
Make sure you include the dash at the beginning.
Close the dialog. Build and run.
There’ll be a lot of code in your Xcode console. Somewhere among the lines, you’ll see entries like this:
Once you enable debug mode, you’ll see several events, and your Xcode console will populate quickly.
Sending analytics data in near real-time is not typical behavior in production.
To be respectful of your user’s battery, Firebase Analytics only sends out analytics data if:
- it’s been sitting around for more than an hour.
- a conversion event is triggered.
- the app goes into the background.
Viewing Events in DebugView
Open the Firebase Console and, under Analytics in the left pane, click DebugView.
Build and run. Order some cookies. When you tap Confirm Order, an event in the timeline will appear.
It might take a while for the events to show, but after a few seconds you’ll see them on the screen:
On the right side, you’ll see a list of events logged in the last 30 minutes. Click an event name to see all of it’s properties:
Exit the view by clicking x.
Viewing Events in the Firebase Console
While debug mode is useful when you’re developing, you’re more likely to view a collection of data under Events in the left pane of the Firebase Console:
Note that it can take up to 24 hours for the events to show.
This report shows the analytics data from all your apps, both iOS and Android.
Big companies often have dedicated teams to track and analyze analytics. There could be hundreds of events tracked in one app, depending on the end goal.
When you have that much data and you’re doing a serious in-depth analysis, you can export your data into BigQuery, which is a Google data warehouse service. This tutorial doesn’t cover BigQuery, but if your app is tracking a lot, it’s worthing looking further into the service.
User Properties and Audiences
While seeing a data collection is nice, sometimes you want to break it into more specific user segments.
It’s great to see people are visiting your in-app store but, who are these people?
Are they new users? Dog owners? Canadians?
Knowing who your users are can make it easier for you to analyze data in greater detail.
Filtering With User Properties
By default, Firebase Analytics provides some segments for you. You can filter any particular event by device type, gender, country and more.
Open the Firebase Console and create a new filter. Click Add Filter in the top left of the Dashboard. Select a user property you want to filter by, like all your iPhone users:
Often you might need more specific data. For that purpose, you can create custom user properties.
You add custom user properties by defining a key-value pair.
After you assign a user property to a user, all events from that point on have that user property associated with them.
You can define more than one user property, but keep them to a small number of discrete values if you want to make your life easier. Having too many events and user properties will only make it harder for you to track who did what and who is who.
Your marketing team has a theory that cat people are more likely to make in-app purchases than dog people. They want to back up that claim with data. This sounds like a job for custom user properties.
Adding Custom User Properties
It’s time to add some functionality to the left questionnaire button on the main screen.
Build and run. When you tap the nose button in the upper left corner, an alert will pop up and ask you whether you’re a cat or a dog person:
Once a user answers the questionnaire, they’ll have a custom user property assigned to them. Because you have a tight deadline, you’ve made sure there’s no exit button on the modal window.
Open ProductListView.swift and add the following to the top of the file:
import Firebase
Adding a user property is straight forward.
You already have the alert view set up, so all you have to do is add a user property to each selection button.
At the bottom of the view’s body
, find the alert
modifier.
You’ll see an empty action for both the dog and cat buttons.
Inside an action of a primary, or cat, button, replace // TODO 3
with:
FirebaseAnalytics.Analytics.setUserProperty(
"cat_person",
forName: "dog_or_cat_person")
Do the same for the secondary, or dog, button. Replace // TODO 4
with:
FirebaseAnalytics.Analytics.setUserProperty(
"dog_person",
forName: "dog_or_cat_person")
You set a user property with setUserProperty(_:forName:)
. Give it the custom name dog_or_cat_person and two values: dog_person and cat_person.
Build and run. Open the questionnaire and select an answer.
Somewhere in your Xcode console, with the debug view turned on, a new line will appear:
It doesn’t tell you much, only that a user property has been set. Play with the app and trigger different events.
Viewing User Properties in DebugView
Open the Firebase Console and click DebugView. You’ll see a new user property recorded in the orange text:
If other events were logged after the user property was set, they’ll each have an assigned user property.
Before you can filter out these events based on a user property’s value, you have to create one in the Firebase Console.
Adding User Properties in the Firebase Console
Still in the Firebase Console, click Custom Definitions in the left pane.
Click Create custom dimensions and a New custom dimension window will appear.
Give your dimension a descriptive name as it’ll appear in all your reports. You can use the same name as the name of your user property.
Under Scope drop-down, choose User. Give it a description.
Copy and paste dog_or_cat_person from Xcode to User property. It’s best to copy and paste it because you can’t rename it once you add the user property. Also, there’s a limit of 25 custom user properties.
Click Save.
From this point on, when the Firebase Console logs new events, you’ll be able to filter them by the value of your custom-defined user property.
So who wins? Do cat people buy more cookies?
Tailoring User Experiences with Audiences
Firebase Analytics is even more powerful with Audiences.
They give you the ability to create groups of users who meet certain criteria. You can think of them as advanced filtering options. They can be broad or narrow and help you deliver personalized user experiences.
Open Audiences in the Firebase Console to see some already added there:
Because you added predefined purchase events, Firebase added Purchasers for you. That’s the beauty of using predefined events.
Consider the next use case.
A user views one or more products in your app, goes to the checkout screen but doesn’t complete the order.
These actions only tells you that the user opened the app, wanted to make an order but dropped it before completing it. That could mean there’s something wrong with the checkout process, the order failed or the user closed the app.
You can’t know for sure.
You can create an audience of these users. Give it a name and define a list of events to log. Think of it as a to-do list where you need to complete all items in the list before you mark the list as finished.
When Firebase detects such events, it puts that user in the specified audience. You can personalize the app only for those specific users by having an audience.
Finally, you can ask those users why they haven’t completed an order with an in-app pop-up screen. You can get concrete feedback from users who are part of that audience without bugging the rest of them.
Where do you think Google gets those personalized ads from? Your friend sends you a message about his trip to the Bahamas, and now, for the rest of your life, you’ll see the Bahamas everywhere.
Where to Go From Here?
Congratulations!
Now you can get insight into what people mean when they leave a two-star review of your app. Not that they ever would!
You can download the completed project files by clicking the Download Materials button at the top or bottom of this tutorial.
You only learned a small part of what Firebase Analytics can do. Explore even more options. For example, try to create some Audiences.
If you don’t know where to begin, the Firebase Official Documentation is a good starting point.
And be sure to check out Firebase Tutorial: Getting Started to learn more about how Firebase can supercharge your app.
If you have any questions as you work with Firebase Analytics in your apps, don’t hesitate to leave a comment in the forum discussion below.