Introduction to Firebase

We are in an era of rapid prototyping. We may get bright ideas, but sometimes they don’t get implemented if they take too much work. Often, the back-end is the limiting factor—many ideas never get implemented due to lack of knowledge or time for server-side coding.

As a mobile developer, using a back-end as a service (BaaS) platform can help you swiftly implement your ideas.

Firebase has all the key features you need for rapid prototyping and quickly testing out your ideas. Using Firebase, you can shortcut the creation of functionality like authentication, database, and object storage. Firebase also comes with other capabilities which can be useful for validating prototypes, such as analytics, A/B testing, and push notifications.

Best of all, Firebase is free for small projects!

Configure an iOS App to Use Firebase

Let’s create a sample Xcode project that uses Firebase. We’ll name it MyFirstFirebaseApp.

Create a New Xcode Project

Choose a Single View App template for your project.

Now that the project is created, let’s start configuring it for Firebase.

Create a Podfile

CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. We need to initialise it in our project. This can be done with the pod init command.

$ cd your-project directory
$ pod init

Add the Firebase Pods

We want to add the Firebase/Core pod to our project. This includes the prerequisite libraries needed to get Firebase up and running.

$ pod 'Firebase/Core'

Now this is how your Podfile will look:

Podfile with Firebase Core

Install the Pods and Open the Project in Xcode

After including the pod details, let’s install them with the pod install command. Then we can open the project in Xcode by opening the .xcworkspace file.

$ pod install
$ open your-project.xcworkspace

Create and Configure Your Firebase Account

Create a Firebase Account

Now let’s get set up with a Firebase account! As we all know, Firebase is a Google product, so we can create a Firebase Console account using our Gmail account.

However, take note: Firebase isn’t completely free. We can start with a free version for initial prototyping, but if you have plans to go into production with Firebase then you should be aware of the pricing structure.

Create a New Project in the Firebase Console

Now that we have logged in successfully to our Firebase account, let’s create a project. Click on Add project.

Once the project is created, the Firebase Database, User Management and Remote Config can be shared with iOS, Android and the web.

Add a project in the Firebase Console

Once the project is created, you’ll be taken to the Project Overview screen. Under Get started, click on iOS to get started on our iOS prototype.

Firebase Project Overview

Register the App for iOS

To register our app, we need to provide a project identifier.

Add Firebase to an iOS AppRegister App

Now click Register app. You’ll be asked to download a .plist file that will need to be added to your Xcode project.

Download infoplist file

This GoogleService-Info.plist will contain basic information like the client id, API Key, database URL, and storage bucket. Have a look and see once you download it. You then need to add it to your project by dragging it to the folder shown below in Xcode.

Xcode project with GoogleService-Infoplist

Add the Initialization Code to Your App

Now you can add the Firebase initialization code to your app! Open AppDelegate, and import Firebase. Then add FirebaseApp.configure() in didFinishLaunchingWithOptions. Your code will look like this:

import UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(_ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?)
    -> Bool {
    FirebaseApp.configure()
    return true
  }
}

Verify That Firebase Is Working in Your App

The setup is finally complete, and you’re ready to test that Firebase is installed correctly in your app. When you click Next on the Add Firebase to your iOS app page in the Firebase Console, you’ll see this:

Run your app to verify installation

Let’s clean, build and run the app through Xcode—there should be no errors. Also you can see some logs related to Firebase in your console. If everything works right, the Firebase Console will let you know.

Hurrah! Now we have successfully set up Firebase for our app.

Firebase User Management

As mentioned earlier, Firebase can be used for user management, so let’s set up our app for authentication and managing users. Firstly, let’s navigate to the Authentication section in the Firebase Dashboard, as shown below.

Authentication section in the Firebase Dashboard

Click on Set up sign-in method. Here we can see a number of possibilities. You can choose more than one, or if you prefer not to have any sign-in, you can choose Anonymous.

  • Email/Password: Allows users to sign up using their email address and password. Firebase SDKs also provide email address verification, password recovery, and email address change primitives.
  • Phone: Allow users to sign in with a mobile phone number using Firebase SDK phone verification and user authentication tools. Under Firebase’s free Spark plan you get 10,000 phone logins a month, but after that you’ll have to pay. Have a look at the pricing section before opting for this.
  • Google: Google sign-in is automatically configured on your connected iOS and web apps. To set up Google sign-in for your Android apps, you need to add a SHA1 fingerprint for each app in your Project Settings.
  • Play Games: Configure Client ID and Client secret.
  • Facebook: To use Facebook for authentication, you’ll have to add an OAuth redirect URI to your Facebook app configuration.
  • Twitter: To use Twitter for authentication, you’ll add a callback URL to your Twitter app configuration.
  • GitHub: To set up authentication with GitHub, you’ll add an authorization callback URL to your GitHub app configuration.
  • Anonymous: Select this option to enable anonymous guest accounts in your application, which lets you enforce user-specific security and Firebase rules without requiring credentials from your users.

Configure Phone Authentication

Let’s see how we can use a phone as a sign-in method.

First, navigate to Sign-in method, click on Phone, and enable it. You’ll see a screen like this:

You’ll also need to include the Firebase/Auth pod in your Podfile.

 pod 'Firebase/Auth'

After adding the above line in your Podfile, navigate to the project folder and run the pod install command.

Next, you need to enable push notifications in your Xcode project.

Enable push notifications

To find this setting, select your app from the Targets panel and click on the Capabilities tab. From there, you can enable Push Notifications.

reCAPTCHA Verification

Now let’s configure reCAPTCHA verification. reCAPTCHA is used in the event that sending or receiving a silent push notification is not possible, such as when the user has disabled background refresh for your app, or when testing your app on an iOS simulator. In this case, Firebase Authentication uses reCAPTCHA verification to complete the phone sign-in flow.

Click on GoogleService-Info.plist in Xcode’s left panel to open the plist. Now copy the value of REVERSED_CLIENT_ID into TextEdit or another notepad.

Next, go to Targets > your app > Info > URL Types. Click on the “+” button and copy the REVERSED_CLIENT_ID value into URL Schemes, as shown below.

URL Types Settings

Configure Firebase Cloud Messaging

Now let’s configure Firebase Cloud Messaging with our app’s APNs.

Open the Firebase Console, and once you click on the Settings button you will see Project Settings and Users and Permissions. Click on Project Settings and then the Cloud Messaging tab. On this screen, you can find the iOS app configuration section.

Firebase Cloud Messaging settings for an iOS app

To enable Firebase Cloud Messaging, we will upload our APNs and our APNs authentication key to this dialog.

You’ll need to create an APNs authentication key and an APNs certificate key.

Steps to Create an APNs Authentication Key

  • In your developer account, go to Certificates, Identifiers & Profiles, and under Keys, select All.
  • Click the add button (+) in the upper-right corner.
  • Enter a description for the APNs auth key.
  • Under Key Services, select the APNs checkbox, and click Continue.
  • Click Confirm and then Download. Save your key in a secure place! This is a one-time download, and the key cannot be retrieved later.

Steps to Create an APNs Certificate Key

  • Create an App ID from your Apple developer account and enable Push Notification while creating. An App ID is an identifier that uniquely identifies an app. As a convention, it is represented by a reversed domain with your company name and the app name (e.g. com.mysoft.myfirstfirebaseApp).
  • Create a Provisioning Profile for the above App ID.

And that’s it! Now, we are done with all the configurations, and we can start implementing the registration and login flow.

Registering a User With Phone Authentication

Let’s go back to Xcode and create the RegistrationViewController.swift, RegistrationViewController.storyboard, and RegistrationService.swift files.

For the storyboard, I have added a UITextField and UIButton as shown below. These should be linked in RegistrationViewController.swift.

The registration storyboard

This is how my RegistrationViewController.swift will look:

import Foundation
import UIKit

class RegistrationViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet weak var phoneNumber: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func requestOTPTapped(_ sender: Any) {
        
    }
}

Since our main focus is on Firebase, we won’t be implementing UITextFieldDelegates. Instead, to keep things simple, we’ll capture the text on button click.

Now let’s add the following code in RegistrationService.swift.

import FirebaseAuth

class RegistrationService {

    func getVerificationId(phoneNumber: String, completionHandler: @escaping (String?, Error?) -> Void){
        
        PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationID, error) in
            
            if let error = error {
                completionHandler(nil, error)
            }
            
            if let id = verificationID {
                completionHandler(id, nil)
            }
        }
    }
} 

In this code, PhoneAuthProvider.provider().verifyPhoneNumber takes a phone number as input and sends us back the verificationID. This also triggers a one-time password (OTP) message to the phone number that was provided in the text field. The user will receive the OTP on their phone and input it back into an alert dialog in the app.

Note: while entering the phone number, make sure the country code is also entered.

Also note that we have to remember to import FirebaseAuth at the top of the file.

Now, let’s go back to RegistrationViewController.swift and call getVerificationId, as shown below. Here, I’m printing the id to the console to check if verificationId was generated.

import Foundation
import UIKit

class RegistrationViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet weak var phoneNumber: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func requestOTPTapped(_ sender: Any) {
        if let phoneNumber = phoneNumber.text{
            
            RegistrationService().getVerificationId(phoneNumber: phoneNumber){ (id, error) in
                if error != nil {
                    return
                }
                
                if let id = id {
                    print(id)
                }
            }
        }
    }
}

The Sign-In Method

Now let’s write a sign-in method in RegistrationService. Here, we’ll create a Firebase Credential object using verificationId and OTP. This is how the code will look:

    func signIn(verificationId: String, verificationCode: String, completionHandler: @escaping (String?, Error?) -> Void){
        
        let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationId, verificationCode: verificationCode)
        
        Auth.auth().signIn(with: credential) { (user, error) in
            
            if let error = error {
                completionHandler("Error", error)
            }
            completionHandler("Success", nil)
        }
    }

Once we receive the id, we’ll show an alert view for user to capture the OTP and call the signIn method in RegistrationService. Here is what the RegistrationViewController will look like after these changes:

import Foundation
import UIKit

class RegistrationViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet weak var phoneNumber: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func requestOTPTapped(_ sender: Any) {
        if let phoneNumber = phoneNumber.text{
            
            RegistrationService().getVerificationId(phoneNumber: phoneNumber){ (id, error) in
                if error != nil {
                    return
                }
                
                if let id = id {
                    self.displayAlert(id: id)
                }
            }
        }
    }
    
    func displayAlert(id: String) {
        let alertController = UIAlertController(title: "OTP?", message: "", preferredStyle: .alert)
        
        let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: {
            (action : UIAlertAction!) -> Void in
        })
        
        let saveAction = UIAlertAction(title: "Save", style: .default, handler: {
            alert -> Void in
            
            let otpText = alertController.textFields![0] as UITextField
            if let otp = otpText.text {
                print(otp)
                
                RegistrationService().signIn(verificationId: id, verificationCode: otp){ (status, error) in
                    if error != nil {
                        return
                    }
                    
                    print("SignIn status", status ?? "Unknown")
                }
            }
        })
        
        alertController.addTextField { (textField : UITextField!) -> Void in
            textField.placeholder = "OTP"
        }
        
        alertController.addAction(cancelAction)
        alertController.addAction(saveAction)
        
        self.present(alertController, animated: true, completion: nil)
    }
}

Now you can run your app to try it out—here’s what you’ll see when you click Request OTP.

Registration OTP Dialog

Now the sign-in status will print as Success. We can check in Firebase Console that a user has been created.

Conclusion

In this tutorial, we built a simple app using Xcode and Firebase. Hopefully, you’ll have gained some new skills which you’ll be able to put into practice in your upcoming projects.

If you have any questions, let me know in the comments below.

Source:: Net Tuts

Leave a Reply

Your email address will not be published. Required fields are marked *