Swift: Add Firebase to Your Project — Chapter 1
Section Overview:1. Introduction
2. Installing Firebase
3. Configure Firebase
4. Saving Data to Firebase
5. Reading Data from Firebase
6. Updating and Deleting
What is Firebase?
Firebase is a Google-backed service that provide us with a cloud based infrastructure that allows us to save and retrieve the data from Google web services. That let us not need to maintain our servers and write server site code because the guy Firebase is taking care of these for us!
Firebase has 3 core services:
- a realtime database
- user authentication
- hosting
Installing Firebase with Cocoapods
First, head over to https://firebase.google.com/ > sign in with your google account > go to console > create a project > add Firebase to your iOS app (follow Google instructions to complete. Note: In step 2, I checked “Copy items if needed” when adding it to my Xcode project because I want to delete the download folder right after. When adding Firebase SDK, you can open your Podfile and add the following pods.)
Tips on terminal: pod init > open Podfile -a Xcode > add the following pods:
pod ‘Firebase’
pod 'Firebase/Core'
pod ‘Firebase/Auth’
pod ‘Firebase/Database’
pod ‘SVProgressHUD’
pod ‘ChameleonFramework’
> pod install
Integrate Firebase into Our Project
- Open up the workspace, import Firebase, initialize and configure the Firebase in AppDelegate
Note: What does AppDelegate do? AppDelegate handles application lifecycle events — i.e., responding to the app being launched, backgrounded, foregrounded, receiving data, etc.
2. Go to Authentication > Click “Sign-in method” > enable Email/ Password
3. change Database Rules as following to make everyone assess the database without restriction
{
"rules": {
".read": true,
".write": true
}
}
Read and Write Data into Firebase
Go to your ViewController > import Firebase> call the reference of database
let planItemsReference = Database.database().reference(withPath: “to-do list”)
let itemRef = self.planItemsReference.child(textField.text!.lowercased())// Save value by passing in a dictionary
let values: [String: Any] = [ "name": textField.text!.lowercased(), "addedByUser": self.user.email, "completed": "not yet"]itemRef.setValue(values)
created a snapshot of firebase:
planItemsReference.observe(.value, with: { snapshot in print(snapshot)})
planItemsReference.child(“sample”).observe(.value, with: { snapshot in let values = snapshot.value as! [String: AnyObject] let name = values[“name”] as! String let addedBy = values[“addedByUser”] as! String let completed = values[“completed”] as! Bool print(“names: \(name)”) print(“added by: \(addedBy)”) print(“completed \(completed)”)})
//load the list of PlanItem to TableViewControllerplanItemsReference.observe(.value, with: { snapshot in var newItems: [PlanItem] = [] for item in snapshot.children { let planItem = PlanItem(snapshot: item as! DataSnapshot) newItems.append(planItem) } self.items = newItems self.tableView.reloadData()})
Updating and Deleting
Updating
Whenever tapping on the list item, the item updates to “sleep” like so:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let cell = tableView.cellForRow(at: indexPath) else { return } var listItem = items[indexPath.row]
let values: [String: Any] = [“name”: “sleep”] listItem.ref?.updateChildValues(values)
tableView.reloadData() }
Deleting
Delete the data from Firebase and UITableView:
Method 1: remove the value
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let listItem = items[indexPath.row] listItem.ref?.removeValue() items.remove(at: indexPath.row) tableView.reloadData() } }
Method 2: set the value to nil
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let listItem = items[indexPath.row] listItem.ref?.setValue(nil) items.remove(at: indexPath.row) tableView.reloadData() }}
Querying Data
Get the all the items created by a username or get a list of items that have been marked as completed. Like updates, querying starts from a reference. Queries return Database Query Objects which you can observe like references.
planItemsReference.queryOrdered(byChild: “completed”).observe(.value, with: { snapshot in var newItems: [PlanItem] = [] for item in snapshot.children { let plan = PlanItem(snapshot: item as! DataSnapshot) newItems.append(plan) } self.items = newItems self.tableView.reloadData()})
🔍download the project to practice: https://github.com/vicky-kuo-contact/Planner