Spring Ahead Sale — Save on Everything.All videos. All books. Now 50% off.

Build your mobile development skills and save! Stay ahead of the rest with an Ultimate book & video subscription. Starting at just $149/year as part of the Spring Ahead sale.

Home iOS & Swift Tutorials

Firebase Analytics: Getting Started

Learn how Firebase Analytics can help you track iOS app usage.

4.8/5 4 Ratings

Version

  • Swift 5, iOS 14, Xcode 12

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.

Note: This tutorial assumes you know the basics of SwiftUI. If you’re new to SwiftUI, check out the SwiftUI: Getting Started tutorial first. You must have Xcode 12 installed to follow this tutorial. Firebase Analytics only works with SwiftPM on Xcode 12 or later.

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:

Cocoabucks app walkthrough in the simulator gif

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.
Note: If you’re not familiar with the concept of mobile analytics, checkout this tutorial on Getting Started with Mobile Analytics.

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:

Firebase welcome screen with first visit

Creating a Firebase Project

Creating a Firebase project is free. Click Create a project. A new window will appear:

Step 1 screen of adding new Firebase project and giving it a name

Name your project Cocoabucks. Accept the Firebase terms and click Continue.

Firebase will ask you to add Google Analytics to your Firebase project.

Step 2 screen of adding a new project to Firebase and enabling Google Analytics

Leave it enabled and click Continue.

Note: If you have existing Firebase projects, some of these steps may not appear as you’ve already made the selections for your account.

The final step is setting your analytics location.

Step 3 of adding new project to the Firebase and selecting your location or the location of your organization

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.

On Firebase Console screen an arrow pointing up to the iOS button that creates a new iOS app in the Firebase project

Registering the App

A new form will open asking you to register your app and enter your app’s bundle ID:

Step 1 screen of adding an iOS app to the Firebase project and giving it a name

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.

Xcode project screen showing steps how to find your apps bundle ID under Settings & Capabilities tab

Note: Not sure how to set up your personal team and bundle ID in Xcode? Check out this Your First App in the App Store tutorial.

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.

Step 2 screen of adding an iOS app to the Firebase project and downloading config file to import it in your Xcode project

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:

Step 3 screen of adding an iOS app to the Firebase project and showing how to import Firebase SDK using CocoaPods

In this tutorial, you’ll install Firebase SDK using SwiftPM.

Note: At the time of writing, Firebase supports installation via SwiftPM in Beta. There are some known issues and you might get an error if you try running the app on your device. If you do, please refer to this workaround to fix it.

Open Xcode and go to FileSwift PackagesAdd Package Dependency:

Xcode project screen showing how to add Swift Package to Xcode project

A new window will open prompting you to enter the package repository URL. Copy and paste https://github.com/firebase/firebase-ios-sdk inside:

Xcode project screen showing step 1 in adding Swift Package and a field to enter package url

Click Next. You’ll see a new window asking you to choose package options:

Xcode project screen showing step 2 in adding Swift Package and suggested settings for import

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:

Xcode project screen showing step 3 in adding Swift Package and a list of all Firebase tools

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:

Document Outline in Xcode showing a list of newly added Swift Package Dependencies

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:

Step 4 screen of adding an iOS app to the Firebase project and how to initialize Firebase SDK in Xcode project using UIKit

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.

Note: Make sure you don’t skip this step. If you do, Analytics won’t work.

Editing Build Settings

Click Cocoabucks in the Document Outline. Choose your target and, under Build Settings, find Other Linker Flags. Add -ObjC inside:

Xcode project showing steps how to add -ObjC flag to Other Linker Flags in the Build Settings tab

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:

Custom image of an event anatomy and how an event has a name that can be a String and parameters that are Dictionary with key value pairs

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 AnalyticsDashboard:

Firebase Console screen showing Dashboard with events that were recorded in the past 30 days

Note: It’ll take approximately 24 hours to see any analytics in the Dashboard. You don’t have to wait to continue with the tutorial but note that you won’t see any analytics inside it.

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:

Xcode project showing a code file and how typing for AnalyticsEvents shows a list of all available predefined events

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.

Confirm your order in Cocoabucks

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:

  1. 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.
  2. There’s a predefined parameter, AnalyticsParameterScreenName, so you add it to the parameters Dictionary.
  3. 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.

Cocoabucks detail view with analytics

It’s time to see some analytics in action and what happens to your app in the background.

Xcode mascot doing magic and showing a bunny from a hat

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 ProductSchemeEdit Scheme. Within the Run event, select Arguments.

In Arguments Passed On Launch, click + and enter -FIRAnalyticsDebugEnabled.

Xcode project screen showing how to enable debug view mode in Edit Scheme

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:

DebugView logs in the Cocoabucks console

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.
Note: Leave debug mode on because you’ll use it for the rest of this tutorial. You can disable debug mode anytime by changing the argument passed on launch to -noFIRAnalyticsDebugEnabled. Then delete and reinstall your app in the simulator since enabling the debug mode is saved to disk.

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:

Firebase Console screen showing DebugView tab and a timeline view of all logged events

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:

Windows with detailed information about a specific event that was selected in the timeline of DebugView

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:

Firebase Console showing Events screen with a list of all logged events in the past 30 days

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:

Firebase Console showing Dashboard screen with filter option turned on to filter users that have used the app on iPhone

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:

iPhone simulator showing running Cocoabucks app and a questionnaire alert screen asking if you're a dog or a cat 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:

Custom analytics event log in Cocoabucks console

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:

Firebase Console screen showing timeline in the DebugView and a user property being set in 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.

Firebase Console showing Custom Definitions window

Click Create custom dimensions and a New custom dimension window will appear.

Firebase Console showing Custom Definitions panel and a new window where you type the information to add a new custom dimension and in this case set a new user property for the events

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.

Note: When you set user-scoped custom dimensions, never include personally identifiable information such as names, social security numbers, or even email addresses.

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?

Creature monster eating a bunch of 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:

Firebase Console showing Audiences screen and how it looks like when there are audiences set up

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.

Funny custom image showing how to distinct certain users and add them to custom audiences

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.

Average Rating

4.8/5

Add a rating for this content

4 ratings

More like this

Contributors

Comments