Thursday 21 February 2019

Realtime chat iOS demo (1) - Firebase Realtime Database

This is a realtime chat iOS demo implemented using Firebase realtime database.  I was impressed that Firebase serverless database provides such a brilliant approach which only took me an hour to finish the core implementation of realtime chat.

You can find the source code here: TarotChatRoom at Github
Hades Mercury



In this chapter, I am going to cover the followings:
1. What can Firebase realtime database provide for this chat demo
2. Preparation and setups
3. Chat room implementation



1. What can Firebase realtime database provide for this chat demo

Firebase realtime database is a Non-SQL database for JSON structured data,  allows write/read/update/delete and most importantly it can notify front-end when any value changes in database.

On the app side when user hits send message button, the new message can be put into the database. When any new message inserted, the database will notify the front-end to refresh and display all messages for the particular conversation. It is so exciting that you don't have to write any backend code. Only thing to do is integrating FirebaseDatabase SDK APIs in your app.


2. Preparation and setups

  • Add project in Firebase console, just follow the steps and put the GoogleService-Info.plist into your xCode project
  • Create a realtime database in Firebase console: Develop -> Database
  • Install SDK in iOS project: Firebase/Core, Firebase/Database,
  • Add FirebaseApp.configure() in Appdelegate didFinishLaunchingWithOptions


3. Chat room implementation

Next to make app talk to database. Here are several core pieces:

DatabaseService to encapsulate FirebaseDatabase APIs. 




databaseName itself is a key to find the child structure which contains records. My realtime database is structured as below in Firebase, so databaseName should be "TarotRoom"

















Note: Since the API returns DataSnapshot type, we have to decode and encode by ourselves. I created a MessageModel conform to DatabaseCodable which improves the reusability of DatabaseService via Generics.


   


Now all the Firebase and Database integration are done. We can just call addRecord(), observeValues() of DatabaseService to make the app talk to database. Any other layers in your app even doesn't need to know how it is implemented. I am using MVVM pattern In my demo and the DatabaseService is injected to the ChatRoomViewModel which can be replaced by MockDatabaseService for testing purpose. However, it is beyond the topic of this chapter. You can find the source code here if interested.


Related chapters:
Realtime chat iOS demo (2) - Firebase Remote Config
Realtime chat iOS demo (3) - Firebase Cloud Storage
Realtime chat iOS demo (4) - Firebase Cloud Function
Realtime chat iOS demo (5) - Firebase Cloud Messaging


No comments:

Post a Comment