How to save data to Firebase in Swift Language (iOS)?

Objectives of the blog

After reading this blog we will be able to install the Firebase SDK in your project and write code to save data to Firebase database along with the creation of the Firebase project.

Pre-requisites

We need to write swift code to save the data to Firebase. For this, first we will have to create the Firebase project. Follow the steps given below to create the Firebase project –

1.Go to https://console.firebase.google.com

2.Click on “Add Project” button

 

Add project

3. Then create iOS app and download GoogleService-Info.plist file

4. Then move the plist file inside the project

5. After than in Xcode, open AppDelegate.swift and add this code before the return statement within application(_:didFinishLaunchingWithOptions:)

FirebaseApp.configure()

6.Then click on “Database” option from the left menu.

 

Database: iOS

7. Select “Realtime Database”, there you will find the database URL, which you can use in the code in order to fetch the data from the database. Generally you will not need this URL as we are using GoogleServices-Info.plist file and the database url is already available in that file, we only need to initialize the Firebase.

8. Firebase setup is completed

Now you will have to download Firebase SDK in the swift. For this you will have to install the following pods.

1. pod ‘Firebase/Core
2. pod ‘Firebase/Database

Let suppose currently we have no data in the Firebase database and we want to save the following data in the given format in the database  –

// The root of the tree
{
  "grocery-items": {
    "milk": {
      "name": "Milk",
      "addedByUser": "Nebula"
    },
 
    "pizza": {
      "name": "Pizza",
      "addedByUser": "Alice"
    },
  }
}

After successfully installing the pods on the project, we are ready to implement the coding part.

Code Implementation

Before creating the references, you will have to understand that what is a Firebase reference.

A Firebase reference points to a location in Firebase where data is stored. Even if you create multiple references, they all share the same connection.

First we will have to create reference of the FIRDatabaseReference.

Reference that will hold root node (grocery-items) can be made by using the following code –

let ref = Database.database().reference(withPath: "grocery-items")

or you can also use the following way –

let rootRef = Database.database().reference()
let ref = rootRef.child("grocery-items")

Then we will have to create reference to the child items which are milk and pizza so that we can add the data inside those nodes.

let milkRef = ref.child("milk")
let pizzaRef = ref.child("pizza")

We know that we need to save dictionary inside these keys. For that we will create two dictionaries one for milk and another for pizza.

let dictMilk: [String: String] = ["name": "Milk", "addedByUser": "Nebula"]
let dictPizza: [String: String] = ["name": "Pizza", "addedByUser": "Alice"]

After that we can add the dictMilk and dictPizza into the milkRef and pizzaRef and these will get added as child of those references.

There are two methods which are used to save data into the Firebase database which are setValue and updateChildValues. If you want to know when your data has been committed, you can add a completion block. Both setValue and updateChildValues take an optional completion block that is called when the write has been committed to the database. This listener can be useful for keeping track of which data has been saved and which data is still being synchronized.

 

// Saving the values in milk node
milkRef.setValue(dictMilk) {
  (error:Error?, ref:DatabaseReference) in
  if let error = error {
    print("Data could not be saved: \(error).")
  } else {
    print("Data saved successfully!")
  }
}
 
// Saving the values in pizza node
pizzaRef.setValue(dictPizza) {
  (error:Error?, ref:DatabaseReference) in
  if let error = error {
    print("Data could not be saved: \(error).")
  } else {
    print("Data saved successfully!")
  }
}

 

After running the code shown above, you will get the same structure in the Firebase database which is already shown.

Summary

After following the above procedure, you will be able to save the data to the Firebase database in swift.

Leave a Reply

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