How to read and write data in Firebase Database for iOS App? And how to get data collection with a certain value?

Rabialco Argana
4 min readNov 30, 2022
Source Image from Wikipedia

Hi Internet people! I’m Rabialco Argana and you can call me Alco. In this article, I want to tell you guys how to read and write data in Firebase and how to get data collection with a certain value. I learn this knowledge when developing my iOS App that using Firebase for it’s database. Below is the outline of my journey.

Outline

— What is Firebase

— Setup Firebase into your Project

— How to read and write data in Realtime Database?

— How to get data collection that has a certain value?

What is Firebase?

Based on the Firebase Official Website, Firebase is an app development platform that helps you build and grow apps and games users love. Firebase provide product such as Back-end infrastructure, monitoring tools, and engagement tools. Back-end infrastructure helps developer to accelerate and scale app development without managing infrastructure such as virtual private server to store their database. Firebase Back-end infrastructure provide such as firestore, real-time database, remote config, extensions, app check, cloud functions, authentication, cloud messaging, hosting, cloud storage, and machine learning that have different utility for developer needs. Back-end infrastructure product that help to store data and be your database for your application in Firebase are firestore, real-time database, and cloud storage.

Setup Firebase into your Project

First thing first, you must create a project. For this tutorial I will be using UIKit iOS App. After finishing creating the project, in the second step, you must setup firebase into your project. You can follow this documentation made by Firebase :

How to read and write data in Realtime Database?

After finishing installation and setup firebase to your project. The next step is to create a file to be your Database Manager in order to communicate with Firebase Cloud Realtime Database. For more detailed explanation you can see Firebase documentation below about how to read and write database for iOS based project :

Here’s the example code snippet to create the DatabaseManager file for saving user detail in Firebase Realtime Database.

//
// DatabaseManager.swift
// test-app
//
// Created by Rabialco Argana on 30/11/22.
//

// MARK: - Import Library
import Foundation
import FirebaseDatabase

final class DatabaseManager {
static let shared = DatabaseManager()

private let database = Database.database().reference()

static func safeEmail(emailAddress: String) -> String {
var safeEmail = emailAddress.replacingOccurrences(of: ".", with: "-")
safeEmail = safeEmail.replacingOccurrences(of: "@", with: "-")
return safeEmail
}
}

// MARK: - Account management
extension DatabaseManager {
public func insertUser(with user: User, completion: @escaping (Bool)-> Void) {
let userDetail = [
"email": user.safeEmail,
"user_uid" : user.userUid,
"first_name": user.firstName,
"last_name": user.lastName
]
self.database.child("users").setValue(userDetail, withCompletionBlock: { error, _ in
guard error == nil else {
completion(false)
return
}
completion(true)
})
}
public func getAllUsers(completion: @escaping (Result<[[String: String]], Error>) -> Void) {
database.child("users").observeSingleEvent(of: .value, with: { snapshot in
guard let value = snapshot.value as? [[String: String]] else {
completion(.failure(DatabaseError.failedToFetch))
return
}
completion(.success(value))
})
}
}

After creating the Database Manager, you can use it to save your data in the firebase realtime database (in this case user data). Here’s the example code snippet to use the DatabaseManager method for saving user detail in Firebase Realtime Database.

//
// AddUserDetailtoFirebase.swift
// test-app
//
// Created by Rabialco Argana on 30/11/22.
//

// MARK: - How to call Database Manager Method to Communicate with Firebase
let user = User(
emailAddress: safeEmail,
userUid: uid,
firstName: firstName,
lastName: lastName)
DatabaseManager.shared.insertUser(with: user, completion: { success in
if success {
UserDefaults.standard.set("\(email)", forKey: "email")
UserDefaults.standard.set("\(firstName)", forKey: "first_name")
UserDefaults.standard.set("\(lastName)", forKey: "last_name")
} else {
self?.showFailedAlert(message: "System error.")
}
})

But this is a easy condition to read data from database. What if, you want to get certain collection by filtering with certain value?

How to get data collection that has a certain value?

// Users Database Scheme
{
"users": [
{ "0" : [
{
"email" : "john.doe@gmail.com",
"user_uid" : "abcdef123456",
"first_name" : "John",
"second_name" : "Doe",
}
],
"1" : [
{
"email" : "doe.johngmail.com",
"user_uid" : "123456abcdef",
"first_name" : "Doe",
"second_name" : "John",
}
],
"2" : [
{
"email" : "lorem.ipsum@gmail.com",
"user_uid" : "a1b2c3d4e5f6",
"first_name" : "Lorem",
"second_name" : "Ipsum",
}
]
}
]
}

Here’s an JSON Example. Do you wonder how to get collection that has certain value such as “abcdef123456" user_id?….

When developing my application i encounter this problem and wondering how to solve my problem. By searching on the internet, this problem can be solve by Query. This an example for get the collection data of a certain value.

//
// DatabaseManager.swift
// test-app
//
// Created by Rabialco Argana on 30/11/22.
//

// MARK: - Import Library
import Foundation
import FirebaseDatabase

final class DatabaseManager {
static let shared = DatabaseManager()

private let database = Database.database().reference()

static func safeEmail(emailAddress: String) -> String {
var safeEmail = emailAddress.replacingOccurrences(of: ".", with: "-")
safeEmail = safeEmail.replacingOccurrences(of: "@", with: "-")
return safeEmail
}
}

// MARK: - Account management
extension DatabaseManager {
public func getUserByUID(with uid: String, completion: @escaping (Result<[String: String], Error>) -> Void) {
let query: DatabaseQuery = database.child("users").queryOrdered(byChild: "user_uid").queryEqual(toValue: uid)
query.observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
let key = (child as AnyObject).key as String
self.database.child("users").child(key).observeSingleEvent(of: .value, with: { snapshot in
guard let value = snapshot.value as? [String: String] else {
completion(.failure(DatabaseError.failedToFetch))
return
}
completion(.success(value))
})
}
}) { (error) in
print(error.localizedDescription)
}
}
}

By using query, it helps me to conquer any kind of requirement when reading data from the database. Hope it helps, ciao!

© 2022 Rabialco Argana. All Rights Reserved.

Resources :

--

--