Skip to main content

Getting started with Firebase Analytics for iOS, Xcode app template on Github


Analytics is one of the ways in which you can know how users use your app and I think it’s very important to know how users use your app. It’s one of the things that we (or I) use at My Day To-Do (MDT) to encourage usage of certain features. What do I mean? I have written in the past that about my Software engineering background and as such my UI/UX skills are not the best. So the first think I think about when users don’t use certain features of my app is probably because they don’t know about it. Hence to compensate for that, I monitor how the app is used, so I know if the users aren’t using the features I think they should, I will add visual cues in the app to make the feature obvious for them. In almost all of the apps that I have developed at My Day To-Do, I have used Firebase Analytics to monitor app usage. In this post, I will just be talking about how to setup an iOS app with Firebase, provide some sample analytics code of the Github repo that I made for this post.

Background

Love this pay per use pricing model, it’s one of the best things to happen for small software based startups. One of the things that early stage startups are always short off, are funds or in our case, a significant lack of it. Firebase falls into this category and is an awesome tool for startups (I am not getting paid by Google to say this).
p.s. I won’t be talking about things such as how to access the Firebase console or creating a Firebase account, there are others that already do a good job of it. Hence, it’s not the best use of my time.

Setup

Let’s pick up from the point, of adding Firebase SDK to your app in the Firebase project creation lifecycle

Add firebase SDK to the project

For this tutorial, in addition to Firebase/Core, let’s also add Firebase/Analytics, remember the focus of this tutorial is to serve as a iOS app Firebase Analytics template. So in the terminal go to the directory where you have created the Xcode project, in my case it’s
/workspace/iOS/OpenSource/ios-firebase-project-template
run the Pod init command and open the newly created Podfile via vim Podfile, move the cursor below
#Pods for Firebase startup template, hit the key and add the following
  pod ‘Firebase/Core’
  pod ‘Firebase/Analytics’
You can save and exit by pressing esc, type wq and hit enter (return) key. Your Podfile should look something like this,
# platform :ios, '9.0'

target 'Firebase startup template' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for Firebase startup template
  pod 'Firebase/Core'
  pod 'Firebase/Analytics'

end
Once saved, run Pod install 
After everything is installed, you will notice that Firebase has created a new file i.e. .xcworkspace (which is a directory, read more about it here). Open your project in Xcode using that and remember, to always use that to open your Xcode project. In it, just add
import Firebase 
and FirebaseApp.configure() in the AppDelegate as instructed on the console. Once you have added, this run your project and the Firebase servers should know your setup is complete.
Phew!!!! Now that we have that setup out of the way, we can start on the good stuff!

Xcode Project template

You can find the code repo on Github over here.  In the Firebase docs, you will see that, there are lots of events that we can log (or track), however in this project, we are only interested in tracking, login, share and swipe events. Hence we will  look at
  1. Login: official docs link
  2. Share: official docs link
  3. SelectContent: official docs link  (to track left or right swipes)
The Xcode project is very straight forward, it’s a single view application with 2 buttons to track login and share and a UIView to track swipe gestures.
Ok before we move on, you may notice some unknown code i.e. Feedback helper, well that’s a really simple class that I add to almost all my iOS apps.
import Foundation
import UIKit
class FeedbackHelper {
    static let fbh = FeedbackHelper()
    func generateHapticFeedback(for impactFeedbackStyle: UIImpactFeedbackGenerator.FeedbackStyle) {
        if #available(iOS 10.0, *) {
        let impactGenerator = UIImpactFeedbackGenerator(style: impactFeedbackStyle)
        impactGenerator.impactOccurred()
      }
   }
}
 Haptic feedback is awesome and I think every app must make use of this. Now let's look at the code for the login and share functions.
@IBAction func login(_ sender: Any) {
    FeedbackHelper.fbh.generateHapticFeedback(for: .heavy)
    AnalyticsHelper.logSignInEvent()
}
@IBAction func share(_ sender: Any) {
    FeedbackHelper.fbh.generateHapticFeedback(for: .heavy)
    AnalyticsHelper.logFirebaseShareEvent()
}
So how does this work in practice? You push the share or login button on the app, it calls these functions, executes whatever auth or share code, generates some haptic feedback and then logs the event to Firebase. Now, before I talk about the Analytics Helper, let’s look at the Swipe actions code.
@IBAction func swiped(_ sender: UISwipeGestureRecognizer) {
    switch sender.direction {
        case .left:
            swipeDirectionLbl.text = "You swipped left"
            AnalyticsHelper.logSelContentEventForFirebase(analyticsConstant: AnalyticsConstants.SWIPE_LEFT)
            break
        case .right:
            swipeDirectionLbl.text = "You swipped right"
            AnalyticsHelper.logSelContentEventForFirebase(analyticsConstant: AnalyticsConstants.SWIPE_RIGHT)
            break
    default:
        break
    }
}
For this one, we determine what the swipe gesture was, update the UILabel and then log an event to Firebase. This one’s a little different as we are logging a Select Content event using a custom data structure i.e. AnalyticsConstant.
Now let’s look at the AnlayticsHelper class
class AnalyticsHelper {

    static func logSelContentEventForFirebase(analyticsConstant: AnalyticsConstants.ANALYTICS_CONSTANT) {
        Analytics.logEvent(AnalyticsEventSelectContent, parameters: [
         AnalyticsParameterItemID: "id-\(analyticsConstant.id)" as NSObject,
         AnalyticsParameterItemName: analyticsConstant.name as NSObject,
         AnalyticsParameterContentType:  analyticsConstant.type as NSObject
         ])
    }
    static func logEventAppOpen() {
        Analytics.logEvent(AnalyticsEventAppOpen, parameters: nil)
    }
    static func logFirebaseShareEvent() {
        Analytics.logEvent(AnalyticsEventShare, parameters: nil)
    }
    static func logSignInEvent() {
        Analytics.logEvent(AnalyticsEventLogin, parameters: [AnalyticsParameterSignUpMethod: "email"])
    }
}
The appOpen, logSignIn or share methods are pretty straight forward, what’s different is the selContentEventForFirebase which takes a parameter of type ANALYTICS_CONSTANT. Here’s what that class looks like, it’s basically got
class AnalyticsConstants {
struct ANALYTICS_CONSTANT {
    var id = ""
    var name = ""
    var type = ""

    init(id:String, name: String, type: String) {
        self.id = id
        self.name = name
        self.type = type
    }
}
static let SWIPE_LEFT = ANALYTICS_CONSTANT(id: "swipe_left", name: "Swipe Left", type: "Swipe")
static let SWIPE_RIGHT = ANALYTICS_CONSTANT(id: "swipe_right", name: "Swipe Right", type: "Swipe")
}
This is just a convenience class to log one of the many select content events through your app. Doing it this way just makes it easier and the app more maintainable in the long run.

Summary

Have a look at the ios-firebase-project-template repo on Github, it’s short, simple and can get you started with tracking how users use your app. I cannot stress this enough, keep track of how users use your app, it will help you understand their behaviour, leading you to take steps to help retain them. If you have any questions, then please leave a comment here. Additionally, I use Firebase, if there’s any other Analytics tool, that you use and think it’s great, then feel free to share in a comment. Hope you found this post useful.
As usual, if you find any of my posts useful and want to support me, buy or even try one of our products and leave us a review on the app store.
My Day To-Do - Smart Task List
Developer: Bhuman Soni
Price: $2.99
My Day To-Do Lite - Task list
Developer: Bhuman Soni
Price: Free+
Snap! I was there
Developer: Bhuman Soni
Price: $1.99

Categories: IOSIOSAPP

Comments

vgjourney said…
The site is really beneficial for everyone to know about this topic. I think if you read blog than you will get some more information from blog. This is really useful blog.VG Journey Private Limited

Popular posts from this blog

Upload to AWS S3 from Java API

In this post, you will see code samples for how to upload a file to AWS S3 bucket from a Java Spring Boot app. The code you will see here is from one of my open-source repositories on Github, called document-sharing. Problem Let’s say you are building a document sharing app where you allow your users to upload the file to a public cloud solution. Now, let’s say you are building the API for your app with Spring Boot and you are using AWS S3 as your public cloud solution. How would you do that? This blog post contains the code that can help you achieve that. Read more below,  Upload to AWS S3 bucket from Java Spring Boot app - My Day To-Do (mydaytodo.com)

Addressing app review rejections for auto-renewing subscription in-app purchase (iOS)

The ability to know what the weather is like while planning your day is a feature of  My Day To-Do  Pro and as of the last update it’s also a part of the  Lite version . Unlike the Pro version it’s an auto-renewing subscription based  in-app purchase (IAP)  in the Lite version. What means is that when a user purchases it, the user only pays for the subscription duration after which the user will be automatically charged for the next period. Adding an  auto-renewing  subscription based IAP proved to be somewhat challenging in terms of the app store review i.e. the app update was rejected by the App Review team thrice because of missing information about the IAP. Therefore in this post I will share my experiences and knowledge of adding auto-renewing IAP in hopes to save someone else the time that I had to spend on this problem. In-App purchase This year I started adding IAPs to My Day To-Do Lite which lead to learning about different types of IAP...

Getting started with iOS programming using Swift (Part 1)

I have not been too fond of Objective-C, which was the primary reason for me to stay away from making iOS apps till now. So what changed? Well Apple has done something very interesting recently and that is the introduction of a new programming language i.e. Swift. Swift is awesome, it almost feels like Python, C++ and Objective-C had a baby with some of their good parts in them. So I have been getting to know Swift and it is an awesome language to program in. What I am going to share with this and a series of blog posts are solutions to some problems that i have encounter while i am trying to finish my first iOS app. The one hurdle that I have encountered while getting started on developing an iOS app is that a majority of the solutions for iOS specific problems provide solutions to them using Objective-C. Which is fair, because Swift has not been around for that long. Anyway let us get started with a few basics, A few basics I would highly recommend having a read of this book...