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.

Benefits of Using Firebase Database

It doesn’t matter whether you are working on a small project or your eyes are on a big one you must need a database to store all your information. If you are working on a small project then you can use this Firebase database. Here are the list of benefits using Firebase database:

1. Helps you to effortlessly manage the data of your store.
2. If data changes anytime all connected devices will receive the updated data in their devices.
3. Firebase real-time database is free to use.
4. Time-Saving.
5. Easy to use & Cross-platform support for SDK.
6. Useful for chatting apps, push notifications, news feed, etc.

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
{
  "movies": [
    "movie1": {
      "name": "Avengers",
      "addedByUser": "John"
    },
 
    "movie2": {
      "name": "Star Wars",
      "addedByUser": "Jane"
    },
  ]
}

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

convert-your-ecommercet
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: "movies")

or you can also use the following way –

let rootRef = Database.database().reference()
let ref = rootRef.child("movies")

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 movieRefAvengers = ref.child("movie1")
let movieRefStarWars = ref.child("movie2")

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

let dictMovieRefAvengers: [String: String] = ["name": "Avengers", "addedByUser": "John"]
let dictMovieRefStarWars: [String: String] = ["name": "Star Wars", "addedByUser": "Jane"]

After that we can add the dictMovieRefAvengers and dictMovieRefStarWars into the movieRefAvengers and movieRefStarWars and these will get added as a 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 movie1 node
movieRefAvengers.setValue(dictMovieRefAvengers) {
  (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
movieRefStarWars.setValue(dictMovieRefStarWars) {
  (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.

Also Read This Articles:

One thought on “How to save data to Firebase in Swift Language (iOS)?

  1. Thanks for the information. I am also working on a small project and looking to use this Firebase database, but there are tons of doubts floating in my head. As you mentioned Firebase real-time database is free to use but I just want to ask you that is there any hidden charges which I’ll have to pay later?

Leave a Reply

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