In this post we will learn Write and Read operation in Firebase Realtime Database using Swift. I already posted a Firebase Authenticate Tutorial before. In this tutorial we will see using Firebase Realtime Database in our iPhone Application. Using Firebase as the application backends gives us more flexibility and we can quickly make apps as we do not need to worry about the server side configuration and coding. So lets see how we can use the Realtime Database feature of Firebase.
Contents
- 1 What is Firebase Realtime Database
- 2 Firebase Realtime Database in iOS App
- 2.1 Video Tutorial
- 2.2 Creating a new Xcode Project
- 2.3 Adding Firebase to The Application
- 2.4 Changing Database Rules
- 2.5 Creating User Interface
- 2.6 Write Operation – Firebase Realtime Database
- 2.7 Read Operation – Firebase Realtime Database
- 2.8 Update Operation – Firebase Realtime Database
- 2.9 Delete Operation – Firebase Realtime Database
- 2.10 Share this:
- 2.11 Related
What is Firebase Realtime Database
- It is a NoSQL Database where data is stored in JSON Tree Structure.
Advantages of Firebase Database
We have the following advantages of using Firebase Realtime Database
- It is a NoSQL database stored in google’s cloud so it is available anywhere.
- Updated in realtime across multiple platforms and multiple users.
- Cross platform database.
- Google hosts the data so you do not need to worry about the hardware and other things.
Modeling Firebase Data Structure
- Considering the following data needs to be stored in Firebase Database.
- The above model is for an SQL Database. But if we want to save it inside Firebase Realtime Database we will save it as.
- Now lets see writing data from iphone application.
Firebase Realtime Database in iOS App
Video Tutorial
- You can go through this video tutorial as well to learn every step in detail.
Creating a new Xcode Project
- First we will create a new SingleView application.
- Now the next step is integrating Firebase into the application.
Adding Firebase to The Application
- This step is already covered in one of the previous tutorial.
- First create a project in Firebase Console. Then follow the instructions of adding Firebase to Xcode Project.
- You can go through this Firebase User Registration Tutorial to know the steps in details.
- So I assume that you have done this part. This part contains
- Creating Project on Firebase Console
- Adding GoogleService-Info.plist to Xcode Project
- Opening YourProjectname.xcworkspace after adding pods.
- The only difference is this time your pod file will be like.
# Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'FIRDBExample' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for FIRDBExample pod 'Firebase/Database' target 'FIRDBExampleTests' do inherit! :search_paths # Pods for testing end target 'FIRDBExampleUITests' do inherit! :search_paths # Pods for testing end end
Changing Database Rules
- The default firebase realtime database rules only allows authenticated users to perform read and write operation to the database. But in this tutorial we are not covering the authentication process.
- So for testing purpose we are changing the rules to public but remember this rules should not be used.
- So go to Firebase Database Rules and modify it as below.
{ "rules": { ".read": true, ".write": true } }
Creating User Interface
- First we will create our User Interface from where we will insert the data to firebase. So create the UI as shown below.
- In the above User Interface we have.
- 2 TextField -> For getting Artist Name and Artist Genre as user input.
- Button -> To add the artist to Firebase Database.
- Label -> To display the success message.
- TableView -> To display all the artists stored in the Firebase Realtime Database.
- Now connect all the Views with ViewController.swift. The process is pressing control and dragging the view element inside your ViewController class. You can use Assistant Window for this. If you are confused about this step you can go to the previous Xcode TextField Tutorial and Xcode Button Tutorial.
- After connecting the Views your ViewController.swift will be like this.
// // ViewController.swift // FIRDBExample // // Created by Belal Khan on 05/03/17. // Copyright © 2017 Belal Khan. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var textFieldName: UITextField! @IBOutlet weak var textFieldGenre: UITextField! @IBOutlet weak var labelMessage: UILabel! @IBOutlet weak var tableViewArtists: UITableView! @IBAction func buttonAddArtist(_ sender: UIButton) { } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
- Now lets add the Artist to our Firebase Database.
Write Operation – Firebase Realtime Database
Importing Firebase
- First we will import Firebase.
// import UIKit //importing firebase import Firebase class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { . .
Configuring Firebase
- Now come inside the function viewDidLoad() here we will configure our firebase.
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //configuring firebase FIRApp.configure() }
Getting Database Reference
- Now we will get a reference to the artists node in our Firebase Database.
//defining firebase reference var var refArtists: FIRDatabaseReference! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. FIRApp.configure() //getting a reference to the node artists refArtists = FIRDatabase.database().reference().child("artists"); }
Adding Artist
- Create a function named addArtist().
func addArtist(){ //generating a new key inside artists node //and also getting the generated key let key = refArtists.childByAutoId().key //creating artist with the given values let artist = ["id":key, "artistName": textFieldName.text! as String, "artistGenre": textFieldGenre.text! as String ] //adding the artist inside the generated unique key refArtists.child(key).setValue(artist) //displaying message labelMessage.text = "Artist Added" }
- childByAutoId() function generates a unique key inside the specified reference. and .key returns the generated key.
- For saving the value inside a specified reference node we use setValue() method.
- Now we just need to call this function on button click.
@IBAction func buttonAddArtist(_ sender: UIButton) { addArtist() }
- Now try running the application in simulator.
- Add 2,3 records and check the firebase database.
- Bingo! The values are getting stored. Now lets see how to fetch the stored values.
Read Operation – Firebase Realtime Database
Building TableView
- We already created a TableView to display the fetched values. So come inside Main.storyboard.
- Select TableView and from the right change the Prototype Cells to 1.
- Now select the created cell from the TableView.
- Now while selecting the cell you will see TableViewCell properties on the right. Here you need to set an Identifier. I have given cell as an identifier.
- Now again select TableView, press control and drag it to the yellow view controller icon in Main.storyboard.
- You have to do the above process twice and select both dataSource and delegate as shown in the image below.
- Now inside our Prototype Cell drag and drop two Labels as we have to show Artist Name and Artist Genre.
- Now we will create a Custom Class for TableView cell. So go to File->New->File and select Cocoa Touch Class.
- Now put the name for your class and make sure it should be a Subclass of UITableViewCell.
- Now come back to Main.storyboard and select the prototype cell, here we have to define our custom class, as shown in the below image.
- Now again open Assistant Editor, this time in a window open the custom class that you created and you have to drag and drop the Labels created in the Prototype cell.
// // ViewControllerTableViewCell.swift // FIRDBExample // // Created by Belal Khan on 11/03/17. // Copyright © 2017 Belal Khan. All rights reserved. // import UIKit class ViewControllerTableViewCell: UITableViewCell { //labels connected @IBOutlet weak var labelName: UILabel! @IBOutlet weak var labelGenre: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
- Thats all for the Custom TableView.
Building an Artist Model Class
- As we have two read 3 values from Firebase Realtime Database, artistId, artistName and artistGenre. So for storing it in a List we will create a model class.
- So create a class named ArtistModel.swift and write the following code.
// // ArtistModel.swift // FIRDBExample // // Created by Belal Khan on 11/03/17. // Copyright © 2017 Belal Khan. All rights reserved. // class ArtistModel { var id: String? var name: String? var genre: String? init(id: String?, name: String?, genre: String?){ self.id = id self.name = name self.genre = genre } }
- Now inside ViewController.swift we will define an array that will store the list of Artist using the above model class.
- So come inside ViewController.swift and modify your code as below.
// // ViewController.swift // FIRDBExample // // Created by Belal Khan on 05/03/17. // Copyright © 2017 Belal Khan. All rights reserved. // import UIKit //importing firebase import Firebase class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { //defining firebase reference var var refArtists: FIRDatabaseReference! @IBOutlet weak var textFieldName: UITextField! @IBOutlet weak var textFieldGenre: UITextField! @IBOutlet weak var labelMessage: UILabel! @IBOutlet weak var tableViewArtists: UITableView! //list to store all the artist var artistList = [ArtistModel]() public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return artistList.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ //creating a cell using the custom class let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell //the artist object let artist: ArtistModel //getting the artist of selected position artist = artistList[indexPath.row] //adding values to labels cell.labelName.text = artist.name cell.labelGenre.text = artist.genre //returning cell return cell } @IBAction func buttonAddArtist(_ sender: UIButton) { addArtist() } override func viewDidLoad() { super.viewDidLoad() FIRApp.configure() refArtists = FIRDatabase.database().reference().child("artists"); } func addArtist(){ //generating a new key inside artists node //and also getting the generated key let key = refArtists.childByAutoId().key //creating artist with the given values let artist = ["id":key, "artistName": textFieldName.text! as String, "artistGenre": textFieldGenre.text! as String ] //adding the artist inside the generated unique key refArtists.child(key).setValue(artist) //displaying message labelMessage.text = "Artist Added" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
- Now we will fetch the values and load it to table view.
Fetching Values from Firebase
- Come inside the method viewDidLoad() and modify it as below.
override func viewDidLoad() { super.viewDidLoad() FIRApp.configure() refArtists = FIRDatabase.database().reference().child("artists"); //observing the data changes refArtists.observe(FIRDataEventType.value, with: { (snapshot) in //if the reference have some values if snapshot.childrenCount > 0 { //clearing the list self.artistList.removeAll() //iterating through all the values for artists in snapshot.children.allObjects as! [FIRDataSnapshot] { //getting values let artistObject = artists.value as? [String: AnyObject] let artistName = artistObject?["artistName"] let artistId = artistObject?["id"] let artistGenre = artistObject?["artistGenre"] //creating artist object with model and fetched values let artist = ArtistModel(id: artistId as! String?, name: artistName as! String?, genre: artistGenre as! String?) //appending it to list self.artistList.append(artist) } //reloading the tableview self.tableViewArtists.reloadData() } }) }
- Again run your application.
- Bingo! artists are fetching. If you will add a new artist then also it will be added to the TableView automatically.
Update Operation – Firebase Realtime Database
- Now lets see how to update the existing values in Firebase Realtime Database.
- For updating an Artist we will click on the Artist then a Popup will open asking for new values and from there we can update the artist.
- You can also read this tutorial about Handling Item Clicks in TableView to know how to implement clicks on TableView.
Building Dialog Box on TableView Item Click
- You need to write this function inside your ViewController.swift file. For more explanation about Dialog Box you can read this Dialog Box with Input Tutorial.
//this function will be called when a row is selected func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //getting the selected artist let artist = artistList[indexPath.row] //building an alert let alertController = UIAlertController(title: artist.name, message: "Give new values to update ", preferredStyle: .alert) //the confirm action taking the inputs let confirmAction = UIAlertAction(title: "Enter", style: .default) { (_) in //getting artist id let id = artist.id //getting new values let name = alertController.textFields?[0].text let genre = alertController.textFields?[1].text //calling the update method to update artist self.updateArtist(id: id!, name: name!, genre: genre!) } //the cancel action doing nothing let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in } //adding two textfields to alert alertController.addTextField { (textField) in textField.text = artist.name } alertController.addTextField { (textField) in textField.text = artist.genre } //adding action alertController.addAction(confirmAction) alertController.addAction(cancelAction) //presenting dialog present(alertController, animated: true, completion: nil) }
Updating Values
- Now lets create the function updateArtist() that we called above.
func updateArtist(id:String, name:String, genre:String){ //creating artist with the new given values let artist = ["id":id, "artistName": name, "artistGenre": genre ] //updating the artist using the key of the artist refArtists.child(id).setValue(artist) //displaying message labelMessage.text = "Artist Updated" }
- Now run the application and check whether it is working or not.
- Bingo! the update is also working fine. Now lets try the delete operation.
Delete Operation – Firebase Realtime Database
- Clicking on the Cancel will delete the artist. So lets see how to do this.
- Again create a function named deleteArtist().
func deleteArtist(id:String){ refArtists.child(id).setValue(nil) //displaying message labelMessage.text = "Artist Deleted" }
- Now just call this method when the cancel button is pressed.
//the cancel action deleting the artist let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in //deleting artist self.deleteArtist(id: artist.id!) }
- Now again try running the application.
- So the delete is also working absolutely fine. Now we learnt all the basic operations Create, Read, Update and Delete.
- If you are facing some issues while doing this app you can get my source code from the below link.
[sociallocker] Firebase Realtime Database Example Swift [/sociallocker]
So thats all for this Firebase Realtime Database tutorial. We covered the Read and Write operation in this Firebase Realtime Database tutorial. In the next post we will cover the Update and Delete operation in Firebase Realtime Database.
If you are having any confusions regarding Firebase Realtime Database and Swift then lets discuss it in comments section. Also share this tutorial if you found this useful. Thank You 🙂
Faheem says
Hi, very good Article.
Thanks for sharing keep up the good work.
Eduardo says
I’m having problem with these lines of the didSelecteRow tableview methods
alertController!.addTextField { (textField) in
textField.text = self.artist.name
}
alertController!.addTextField { (textField) in
textField.text = self.artist.genre
}
//adding action
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
//presenting dialog
present(alertController, animated: true, completion: nil)
asking me if it isnt viewcontroller instead of alercontroller
Danilo Mozer says
You have to create an alert controller first, named “alertController”. Here is an example:
let alertController = UIAlertController(title: “Here goes your title”, message: “And here goes your message”, preferredStyle: .alert)
Dinh Van Tin says
good tutorial
Ananya says
Hello,
This an awesome tutorial. One of the best ones I have seen so far. But I am getting the following run time exception while doing the second video , i.e. the data retrieval from fireball part. Any idea about why its throwing this error
Error:
2017-06-04 11:54:36.156 InvestmentTracker[1738] [Firebase/Analytics][I-ACS003007] Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
2017-06-04 11:54:36.266038-0400 InvestmentTracker[1738:98805] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/greeshmamidhun/Library/Developer/CoreSimulator/Devices/E31EB136-3BB0-4B2F-8F0A-703F2F441A93/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
(lldb)
Ananya says
Sorry forgot to paste the line throwing the error:
These are the lines :
let utility = UtilityModel(id:utilityId as! String?, uName:utilityName as!String? , uStartdate:billingStartDate as! String?,uEnddate:billingEndDate as!String?,amount:amount as! Double?)
evelima says
Waiting for “next post we will cover the Update and Delete operation”
Coud add upload and retrieve images too!
Belal Khan says
You can check this youtube playlist
It is complete
Tarun Rajput says
Really nice tutorial ,,but i want get data for a particular id then how to get a particular record.Please reply
georg says
Thank you for the tutorial. But I have a question. When I start the app, the TableView is empty, the data from firebase database doesn`t show up. But when I add a new artist, the other ones also appear on the tableView. I made the tutorial step by step what did i wrong?
georg says
i could figure it out, don`t need help anymore 🙂
Derrick says
How did you fix it?
lenina says
I want to write the data in a seperate view controller can you help me?
Charles Porth says
How would I pull the key from firebase of an already created cell and create that as a var? I want to know this so I can transfer the key into the next view so I can make a generic view but the textfields change with the key.
Sean says
Thanks for your great tutorial.
Can I ask where to download the source code? I mean, the whole project. After I followed the steps, the simulator shut down for no reason. If there’s a complete project for download, it’ll be easier to find out why.
Thanks again
Kevin says
Thanks for your tutorial! But how do you go about making sure that your values in Firebase does not have a duplicate?
Umut says
Ty for this tutorial bro. Awesomeee!!
Jitendra Puri says
I am using version 9.2 of Xcode and am getting compiler error message ” Use of undeclared type ‘DatabaseReference’ ”
import UIKit
import Firebase
class ViewController: UIViewController {
var refIndividual: DatabaseReference! (ERROR is on this line !!!!!!!)
@IBOutlet weak var NameTextField: UITextField!
@IBOutlet weak var MemberOfTextField: UITextField!
@IBOutlet weak var LabelMessage: UILabel!
@IBAction func AddName(_ sender: Any) {
addRecord()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
refIndividual = Firebase.database().reference().child(“Individuals”)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addRecord(){
let key = refIndividual.childByAutoId().key
let Individual = [“Id”:key,”Individual”:NameTextField.text! as String,”MemberOf”:MemberOfTextField.text! as String]
refIndividual.child(key).setValue(Individual)
LabelMessage.text = “Individual Added”
}
}
TomT says
How do you delete =all+ records in a Firebase database?
Thanks – this page was a great help to me.
tomt
Ralf Bordé says
Hi, very good article. THX.
But now i want to select only items with “house” in the artistName. (i have some in the DB)
This is my function which always brings 0 hits.
@IBAction func BTSelect(_ sender: Any) {
DBref = Database.database().reference().child(“artists”)
let query = DBref?.queryOrdered(byChild: “artistName”).queryEqual(toValue: “house”)
query?.observe(.value, with: { (snapshot) in
for childSnapshot in snapshot.children {
print(“childSnapshot:-> \(childSnapshot)”)
}
})
}
Can you say why? What’s wrong in this code?
Thx for checking.
Greeting
Ralf
Amanda says
Incredible article. Thank you!!!!!
Ray Johnson says
Hi everyone! I was having a hard time choosing a good backend service for my apps, so just wanted to share my experience with you on that. Having some apps both at Google Play and Appstore, I used Parse until Facebook decided to shut it down. So, I was forced to search for alternatives and, to be honest, was not that happy as most of them didn’t fit my requirements as nicely.
Firstly, I checked Firebase, but it’s very limited in querying and indexing working on a nonSQL ecosystem with the database being a giant JSON doc. Then, it was AWS and Appery, both are not user-friendly and become rather expensive in no time. My next try was Kinvey, and it’s super expensive once you start doing something complex. I needed system to support social login, like Facebook, Twitter, Google, geolocation, and push notifications for both iOS and Android, so my final try was Backednless, I started for free and was able to figure out how to use it a lot faster than before, since support is pretty fast to answer. So far, it fits all of my needs and functionality is on point. Hope this helped.