Get updates on your email

Friday, September 15, 2017

Getting Started on Firebase for iOS | Beginner's Tutorial

In this tutorial we will develop an iOS app which will use Firebase as a backend. The app is called GroceryBit and it's a simple app where a wife can add grocery items to the list of her husband and he can view them on his phone.

Starting iOS Firebase Project:

First step is to create your xcode project because you need bundle identifier while creating the project on firebase. Here is my xCode new project creation screenshot:

Open and login.

After login add a new project

Fill the details and create project

Select Add Firebase to your iOS app

Here you need to add the bundle Id and give it a nickname (optional) and register the app.

Next step is to download the configuration file

Click on Download GoogleServices-Info.plist file. Once it is downloaded close this and we will do step number 3 and 4 later.

Configuration of xCode project:

Open xCode Project and drag and drop the downloaded .plist file into your project. Don't forget to check copy items if needed when you drop the file.

Installing Firebase library via Cocoapods:

We will import firebase library using cocoapods. I'm assuming you already have them installed but if you don't know how to install cocoapods click here to view the tutorial for it.

In your Podfile you need to add:

pod 'Firebase/Core'
pod 'Firebase/Database'

Then open terminal:

$ cd <path to project folder>
$ pod install

That is it for installing firebase from cocoapods, now moving back to xcode.

Initializing firebase in app:

Open xcode and press cmd+ B just to make sure everything is installed properly then open AppDelegate.swift

import Firebase
and in didFinishLaunchingWithOptions launchOptions:
add FirebaseApp.configure()

Make the UI of your app as per your idea I've made it like this:

and I've made it's classes and made the IBOutlets of the buttons and table.

How Firebase Data is Stored

This section is just for practice and has nothing to do with the actual app we are building. It'll help you understand how firebase data is stored on database.

Go to your firebase console and select database
Note that Firebase database is not the typical DB you'll be using with tables etc. It more of a JSON tree where you have a key and a value. By selecting database you'll see this screen.

Hover mouse pointer on project in my case it's grocerybit-3f536: null and you'll see a + sign next to it.

Clicking the plus sign you'll be presented with text fields for name and value. Name is like key in JSON and value is value. Add data in it just to check:

As I've mentioned it's like JSON structure so in JSON there are some keys which have nested values. But first delete the values you've just added because we don't need them it was just to give you a knowhow. Hover your mouse pointer on any value and You'll see a X sign next to it.
You'll be presented with a prompt for confirmation of delete.

To make nested JSON like structure hover on grocerybit-3f536: null again and click +
Just give a name and no value

You'll not press add at this time but you'll click on the + sign next to value text field to make a child.

 If you want to go even more nested you will do the same give it a name and without giving value click +

So I've made tasks and in tasks we have task1 and inside of that we have information about task 1. Now click ADD and you'll see a tree like structure.

Similarly add another task and fill some data in it.

 And finally you'll DB will look like this

Not that you do not want to add so many nested levels because that might complicate things. Think of it like in DB you normalize tables it's the same for that. So let's go ahead and add another branch from node (root) of this tree.

That is it for practice. Hope so by now You'll have an overview of how firebase data is stored. So let's get back to the app.

Changing rules of data read and write on Firebase

By default it is not allowed for an unauthenticated user to read or write data to your firebase. So in order to move to app we need to change these permissions however these changes are not recommended but for this tutorial only we need these settings in order to understand the basics.

Select rules tab which is next to data tab in database.

Change all the code written in this to

  "rules": {
    ".read": true,
    ".write": true

Publish these changes and you'll see

That's it for permissions.

How to write data to Firebase Database

Make sure you've removed all of the trees which we have made earlier.
Open the class in xcode which is associated with your viewcontroller which will be adding the value to the database and in this class

import FirebaseDatabase

and declare this variable
var ref: DatabaseReference?

In viewDidLoad() add

ref = Database.database().reference()

In the UI that I made I made action for a button which was + button. Under this action add:


This line above will create a child called "Items" if it is not already created and childByAutoID will generate an auto ID for the entry and set it's value to be the value in the text field.

Run the code and when you'll click add (+) button from your app you'll see the data is added in firebase.

Read Data from Firebase Database

I've a viewController with table view on which I'll be showing the data which I'll retrieve from firebase

We will start with the same

import FirebaseDatabase

and declare a reference variable
var ref: DatabaseReference?
but for retrieving we need an additional variable
var databaseHandle: DatabaseHandle?
and an array to store data in
var postData = [String]()
and in viewDidLoad add
ref = Database.database().reference()
You also need to add tableview delegate and datasource methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return postData.count
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell")
        cell?.textLabel?.text = postData[indexPath.row]
        return cell!

in viewDidLoad after you have provided ref initialization add

databaseHandle = (ref?.child("Items").observe(.childAdded, with: { (snapshot) in
        let post = snapshot.value as? String
            if let actualPost = post {

Here is what this code is doing:
  • ref.child is referring to the child node in firebase and observing if a child value is added. It'll keep on listening so when there is a new value added it should update it on tableview.
  • Snapshot is a variable which we will use to get the value of the added item in DB.
  • To avoid any nil value we have used if let
  • Inside this block we have added actualPost value in the array and then reloadData reloads the tableView

Run the code and add you'll see your table view is being updated with the values from firebase.

here is a trick. Add a new value from firebase and see it will update on table view instantly.

As I click add without re running the app it'll update the value

so this is it for the basics of firebase database. We will be doing auth in next tutorial.

No comments:

Post a Comment