Table of Contents
Introduction
A mobile application is a basic necessity for every organisation which is a must that a business should have. Mobile application service is a basic term that every IT sector creates and every business uses it. With immense usage of it, there are various programming languages and frameworks out there for Javascript, to Python development that can create mobile apps and from all of them Firebase Firestore is the one that provides an easy and secure way to sign into their apps for Android and iOS platforms.
Firebase v/s Firestore
People usually get confused assuming that it’s the same with a different word, but the truth is that they differ from each other.
What is Firebase?
Firebase is a BaaS (Backend-as-a-Service) platform which is a NoSQL database which is better and conventional compared to relational databases.
Firebase is more convenient for developers who use the basic Google account to log in to the Firebase account. Many organisations mostly prefer Firebase for the usability it offers such as
- Real-time Database: Enables developers to store and sync data in real-time efficiently.
- Cloud Firestore: refers to the NoSQL database that can store and sync data for server-side and client-side programming purposes.
- Cloud Function: It’s one of the important features as it’s a serverless feature which it allows the developers to run backend code to respond to the components of Firebase and HTTPS requests.
- Authentication: it refers to a full-fledged, toked-based authorization for a smooth integration of the application.
- Cloud Storage: It’s a feature-rich object storage service for the development of applications. It is a cost-friendly service that assigns Google-level security for the download and upload of files.
What is Firestore?
It’s part of Google Firebase app development software which is a cloud-hosted with NoSQL database option for the storage and synchronization of data. Users can directly access Firestore from their mobile and web applications with native SDKs.
Users can use it with programming languages such as Java, Unity, Go, Node.js, and C++ SDKs, and there is also support for RPC and REST APIs.
Many developers rely on Google Firestore to keep their applications updated in real-time once any changes are dome from the back end side.
- Offline Synchronization : It performs caching of data being used by an app to let it read, write, query, and listen to data even with an offline device.
- Data Structure: User can store their data as documents. Documents contain complex nested objects and subcollections.
- Expensive Querying: It enables the use of queries for fetching specific individual documents or retrieving documents matching query parameters from a collection.
- Scalability: It’s quite scalable for multi-regional replication, atomic batch operations, assurance of consistency, and support for real transactions.
So, it clearly explains that these tools are very essential in app development as they focus on a strong backend and deliver a great user experience. So. let’s dive deep into how to use Firebase with your iOS application.
Using Firebase Firestore in an iOS App
Firebase is a software development where you can build a robust iOS application without writing down any server code. Moreover, it manages database authentication, API and push notifications as well. So, here are some features you will leverage will implementing Firebase in your iOS application.
- Web Asset Hosting
- Realtime crash reporting
- Simple Authentication process
- Cloud storage
- Run code without a server
- Performance tracking
Step 1: Create a New Firebase Project
So, let's begin by creating an account in Firebase through firebase. Once the account is created you can select Add Project in Firebase Console.
After selecting Add Project a dialog box will pop out which requires the name of the project. After adding up the project name Firebase is ready to start with your project.
Step 2: Adding iOS to your Firebase Project
The above dialogue box image is an overview while you create your project. As you are done with creating your project you need to select the iOS tab to add the iOS application after which you will view results like this.
Nickname, Store ID, and iOS bundle ID are required to access the earlier-mentioned image. You are not required to enter the Nickname and Store ID; as they are optional fields.
The bundle ID is the same ID that you created when you made an Xcode project. Also, you can find your Bundle Identifier in the General tab for your app's primary target in Xcode.
<Do a double-check on your bundle ID and make sure it starts with .com. After filling up the details. Hit the register app button to continue the process.
Step 3: Add Firebase Configuration File In Your Code Project
Here you now need to download the configuration file.
The above image shows the GoogleService-info.plist file that you need to download and insert into your Xcode Project. Once, you are done with this, Hit NEXT.
Step 4: Install Firebase SDK using Cocoa Pods
Coca Pods plays a vital role in installing a Firebase SDK in your Xcode project. Once you have installed Cocoa pods next you need to add pod ‘Firebase/Core to your Podfile and then run pod installs.
# platform: ios, ‘9.0’
target ‘list’ do
use_frameworks!
pod ‘Firebase/Core’
pod ‘Firebase/Firestore’
end
Your project code is included in XCWorkspace along with your pods. Xcodeproj is the new replacement for it. For your project, you need to utilise the earlier one.
Step 5: Configure Firebase in App Code
Now, you need to add an installation code to your project. By adding this code you will set up a Firebase when your app starts, you just need to copy and paste it from the Firebase website.
Now, you need to run your app and verify a successful installation where Firebase will check for the correct installation.
Step 6: Connectivity with Firebase Database
To show how this function works let’s run through a basic list application. It will demonstrate how to establish a connection and sync in real time with the Firebase database.
You'll be able to observe how updates made on the web are reflected in the app and vice versa. Let's observe its operation.
Open the Firebase and click on the database which is under the develop section on the left panel.
Next, you will be given an option you will be given to use Cloud Firestone or Realtime Database.
We will begin with the test mode as it doesn't require any additional setting up permission with a rapidly developing application.
By clicking on the Enable button it allows you to set up a Firebase in your Cloud Firestore.
Next, click on the add collection and name its item
Over here we will add the first item in our collection as it’s just a demo the type will be mentioned as the string.
By adding up the collection ID your database will be set up which looks as follows
Next, let’s retrieve and display the data in our application. Add pod ‘Firebase/Firestone’ to your Podfile and run pod install.
Xcode has a view controller which you need to open and it launches when your application starts.
import UIKit
import Firebase
class MainViewController: UIViewController {
override func viewDidLoad() {
super. viewDidLoad()
let db = Firestore. firestore()
db. collection (‘items”). getDocuments() { (querySnapshot, err) in
if let err = err {
print(“Error” getting documents: \(err)”)
}
else {
for document in querySnapshot!. Documents {
print (“\ (document. document ID) => \(document. data())”)
}
}
}
}
}
You also need to import Firebase at the top of your file. So, when you run your app you should be able to read in the console
1 => [“name”: Buy toothpaste]
So, now it's visible in the user interface
Next you need to create an XIB file and create a table view. You need to expand it by which it fills up the view and set constraints for leading, trailing, top and bottom
Next, we will have to subclass UITableViewDelegate & UITableViewDataSource in our controller view and add an IBOutlet to the table view. An array to store all the items retrieved from the database. Below is the view controller image.
import UIKit
import Firebase
class MainViewController: UIViewController, UITableViewDelegate, UITabelViewData
@IBOutlet weak var tableView: UITableView!
var items = [String] ()
Now for the setup you need to add viewDidLoad function
tableView. register( UITableViewCell. self, forCellReuseIdentifier: “cell” )
tableView. delegate = self
tableView. dataSource = self
Next we need to complete the table view data source and delegate functions.
func numberOfSectionInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) ->
Return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
let cell= tableView. dequeueReuseableCell(withIdentifier: “cell”, for IndexPath;
cell.textLabel? .text = items [indexPath.row]
return cel
}
So, here is the complete view of the code which will be followed as
import UIKit
import Firebase
class MainViewController: UIViewController, UITableViewDelegate,UITableViewData!
@IBOutlet weak var tableView: UITableView!
var items = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.delegate = self
tableView.dataSource = self
let db = Firestore.firestore()
db.collection("items").getDocuments() { (querySnapshot, err) in
if let err err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot! documents {
if let name = document.data() ["name"] as? String {
self. items.append(name)
}
}
self.tableView.reloadData()
}
}
}
func numberOfSections InTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: inc cell.textLabel?.text = items [indexPath.row]
return cell
}
}
Adding another document in Firestore would look like this
Further, let’s discuss how to write a database and an item to your list with one single click on the button.
I removed the interface builder's table view's bottom limitation. I then made the button smaller and positioned it at the bottom of the screen. This image is below
Drag the buttons inside IBOutlet into our swift file like
Add the following code
@IBAction func addItemClicked(_ sender: Any) {
var ref: DocumentReference? = nil
ref= db.collection("items").addDocument (data: [
“name”: “new item!”,
]) { err in
if let err = err {
print (“Error adding document: \(err)”)
} else {
print(“Document added with ID: \(ref!. documentID)”)
}
}
reloadTable()
}
To make my read code look like this in the file, add new lines to empty the items array.
let db = Firestore.firestore()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.delegate = self
tableView.dataSource = self
reloadTable()
}
func reloadTable() {
Items = [String]()
db.collection("items").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
}
if let name = document.data() ["name"] as? String { self.items.append(name)
}
self.tableView.reloadData()
}
}
}
Launch your application now, and to add new items, click the button at the bottom of the screen.
The Firestore console in Firebase will also reflect the new items.
Conclusion
This comprehensive tutorial, on hiring iOS app developers will gain the ability to implement a smooth Firebase Firestore in their mobile application. The power of Firestore may be used by developers to build dependable, scalable, and responsive iOS apps that fulfil all the needs and requirements that an organization seeks.