Lesson 7. Firebase: auth, db & storage

In this lesson you'll learn about iOS' integration with Firebase.

Micro Sprint 7
Activity Type Lesson
Expected Duration 30 minutes
Topic Fragments
Objective Learn about Firebase integration.

1. Introduction

As seen on Firebase Documentation

Firebase helps you build better mobile apps, without managing infraestructure. Providing on-demand services such as databases, analytics, messaging and authentication, Firebase lets you focus on your app and on your users. It is built on top of Google's Cloud Platform and can scale automatically as much as you need it to.

2. Installing Firebase on your project

First of all, create an Xcode project. Then, create a Podfile if you don't have one:

pod init

Now, add the pods that you wish to install, in this case include Firebase/Core:

pod 'Firebase/Core'

Finally, install the pods and open the Xcode workspace.

3. Available pods

Pod Service
pod 'Firebase/Core' Prerequisite libraries and Analytics
pod 'Firebase/AdMob' AdMob
pod 'Firebase/Messaging' Cloud Messaging
pod 'Firebase/Database' Realtime Database
pod 'Firebase/Invites' Invites
pod 'Firebase/DynamicLinks' Dynamic Links
pod 'Firebase/Crash' Crash Reporting
pod 'Firebase/RemoteConfig' Remote Config
pod 'Firebase/Auth' Authentication
pod 'Firebase/Storage' Storage
pod 'Firebase/Performance' Performance Monitoring
pod 'Firebase/Firestore' Cloud Firestore
pod 'Firebase/Functions' Cloud Functions for Firebase Client SDK

4. Setup Firebase Authentication

As seen on Firebase Documentation

Firebase can manage your users authentication with Google, Facebook, Twitter, GitHub, Phone and even your custom auth provider. To use it you must add the Authentication pod to your Podfile:

pod 'Firebase/Auth'

To create a new user with email and password, complete the following steps:

  1. Import the Firebase module in your UIApplicationDelegate:
import Firebase
  1. Configure a Firebase App
  1. Create a new user by capturing their email and password:
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
  // ...

In order to sign in your created user, just use:

Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
  // ...

5. Cloud Firestore (beta)

As seen on Firestore Documentation

Firebase Firestore is a flexible, scalable database hosted by Google Platform. It supports flexible and hierarchical data structures by using Documents and Collections in a mongo-like manner. To use it, you must install the Firestore pod:

pod 'Firebase/Firestore'

To add and retrieve data from Firestore, follow the next steps:

  1. Import the Firestore module and create a database instance:
import Firebase
let db = Firestore.firestore()
  1. Now, add some data to your database:
// Add a new document with a generated ID
var ref: DocumentReference? = nil
ref = db.collection("classes").addDocument(data: [
    "class": "Moviles",
    "year": 2018,
    "semester": 1
]) { err in
    if let err = err {
        print("Error adding document: \(err)")
    } else {
        print("Document added with ID: \(ref!.documentID)")
  1. Now, in order to read the data from the Firestore database:
db.collection("classes").getDocuments() { (querySnapshot, err) in
    if let err = err {
        print("Error getting documents: \(err)")
    } else {
        for document in querySnapshot!.documents {
            print("\(document.documentID) => \(document.data())")

If you want to learn more about Firebase Firestore in iOS, we encourage you to watch this video ! (Video)[https://youtu.be/rvxYRm6n_NM]

6. Firebase Storage

As seen on Firebase Storage Documentation

Firebase Storage is a Cloud service included in Firebase. It lets you handle file uploads and downloads with ease and secutiry. To use it you must add the Storage pod to your podfile:

pod 'Firebase/Storage'

To initialize an instance you must:

import Firebase
let storage = Storage.storage()

Now that you have an instance you can start uploading and downloading files from the server.

To upload a file, first create a reference to the file in the bucket:

// Create a root reference
let storageRef = storage.reference()

// Create a reference to "mountains.jpg"
let mountainsRef = storageRef.child("mountains.jpg")

// Create a reference to 'images/mountains.jpg'
let mountainImagesRef = storageRef.child("images/mountains.jpg")

// While the file names are the same, the references point to different files
mountainsRef.name == mountainImagesRef.name;            // true
mountainsRef.fullPath == mountainImagesRef.fullPath;    // false

Once you have the reference to the file, you just need to use putData:metadata:completion:

// Data in memory
let data = Data()

// Create a reference to the file you want to upload
let riversRef = storageRef.child("images/rivers.jpg")

// Upload the file to the path "images/rivers.jpg"
let uploadTask = riversRef.putData(data, metadata: nil) { (metadata, error) in
  guard let metadata = metadata else {
    // Uh-oh, an error occurred!
  // Metadata contains file metadata such as size, content-type, and download URL.
  let downloadURL = metadata.downloadURL

To download a file (you could just use the absolute url, but in this case we are going to do it programatically):

// Create a reference with an initial file path and name
let pathReference = storage.reference(withPath: "images/stars.jpg")

// Create a reference from a Google Cloud Storage URI
let gsReference = storage.reference(forURL: "gs://<your-firebase-storage-bucket>/images/stars.jpg")

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
let httpsReference = storage.reference(forURL: "https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg")

// Create a reference to the file you want to download
let islandRef = storageRef.child("images/island.jpg")

// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
islandRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
  if let error = error {
    // Uh-oh, an error occurred!
  } else {
    // Data for "images/island.jpg" is returned
    let image = UIImage(data: data!)

Version Author Date
1.0 Juan Santiago Acevedo April 9, 2018

results matching ""

    No results matching ""