BlogAnnounced at MongoDB.local NYC 2024: A recap of all announcements and updatesLearn more >>
MongoDB Developer
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right

Building a Mobile Chat App Using Realm – Integrating Realm into Your App

Andrew Morgan20 min read • Published Feb 17, 2022 • Updated Apr 06, 2023
Facebook Icontwitter iconlinkedin icon
Rate this tutorial
This article is a follow-up to Building a Mobile Chat App Using Realm – Data Architecture. Read that post first if you want to understand the Realm data/partitioning architecture and the decisions behind it.
This article targets developers looking to build the Realm mobile database into their mobile apps and use MongoDB Realm Sync. It focuses on how to integrate the Realm-Cocoa SDK into your iOS (SwiftUI) app. Read Building a Mobile Chat App Using Realm – Data Architecture This post will equip you with the knowledge needed to persist and sync your iOS application data using Realm.
RChat is a chat application. Members of a chat room share messages, photos, location, and presence information with each other. The initial version is an iOS (Swift and SwiftUI) app, but we will use the same data model and back end Realm application to build an Android version in the future.
If you're looking to add a chat feature to your mobile app, you can repurpose the article's code and the associated repo. If not, treat it as a case study that explains the reasoning behind the data model and partitioning/syncing decisions taken. You'll likely need to make similar design choices in your apps.
Update: March 2021
Building a Mobile Chat App Using Realm – The New and Easier Way is a follow-on post from this one. It details building the app using the latest SwiftUI features released with Realm-Cocoa 10.6. If you know that you'll only be building apps with SwiftUI (rather than UIKit) then jump straight to that article.
In writing that post, the app was updated to take advantage of those new SwiftUI features, use this snapshot of the app's GitHub repo to view the code described in this article.


If you want to build and run the app for yourself, this is what you'll need:


The iOS app uses MongoDB Realm Sync to share data between instances of the app (e.g., the messages sent between users). This walkthrough covers both the iOS code and the back end Realm app needed to make it work. Remember that all of the code for the final app is available in the GitHub repo.

Create a Realm App

From the Atlas UI, select the "Realm" tab. Select the options to indicate that you're creating a new iOS mobile app and then click "Start a New Realm App":
Create Realm App
Name the app "RChat" and click "Create Realm Application":
Create Realm App
Copy the "App ID." You'll need to use this in your iOS app code:
Copy Real App Id

Connect iOS App to Your Realm App

The SwiftUI entry point for the app is RChatApp.swift. This is where you define your link to your Realm application (named app) using the App ID from your new back end Realm app:
Note that we created an instance of AppState and pass it into our top-level view (ContentView) as an environmentObject. This is a common SwiftUI pattern for making state information available to every view without the need to explicitly pass it down every level of the view hierarchy:

Application-Wide State: AppState

Views can pass state up and down the hierarchy. However, it can simplify state management by making some state available application-wide. In this app, we centralize this app-wide state data storage and control in an instance of the AppState class.
There's a lot going on in AppState.swift, and you can view the full file in the repo.
Let's start by looking at some of the AppState attributes:
user represents the user that's currently logged into the app (and Realm). We'll look at the User class later, but it includes the user's username, preferences, presence state, and a list of the conversations/chat rooms they're members of. If user is set to nil, then no user is logged in.
When logged in, the app opens two realms:
  • userRealm lets the user read and write just their own data from the Atlas User collection.
  • chatsterRealm enables the user to read data for every user from the Atlas Chatster collection.
The app uses the Realm SDK to interact with the back end Realm application to perform actions such as logging into Realm. Those operations can take some time as they involve accessing resources over the internet, and so we don't want the app to sit busy-waiting for a response. Instead, we use Combine publishers and subscribers to handle these events. loginPublisher, chatsterLoginPublisher, logoutPublisher, chatsterRealmPublisher, and userRealmPublisher are publishers to handle logging in, logging out, and opening realms for a user:
When an AppState class is instantiated, the realms are initialized to nil and actions are assigned to each of the Combine publishers:
We'll later see that an event is sent to loginPublisher and chatsterLoginPublisher when a user has successfully logged into Realm. In AppState, we define what should be done when those events are received. For example, events received on loginPublisher trigger the opening of a realm with the partition set to user=<id of the user>, which in turn sends an event to userRealmPublisher:
When the realm has been opened and the realm sent to userRealmPublisher, the Realm struct is stored in the userRealm attribute and the local user is initialized with the User object retrieved from the realm:
chatsterLoginPublisher behaves in the same way, but for a realm that stores Chatster objects:
After logging out of Realm, we simply set the attributes to nil:

Enabling Email/Password Authentication in the Realm App

After seeing what happens after a user has logged into Realm, we need to circle back and enable email/password authentication in the back end Realm app. Fortunately, it's straightforward to do.
From the Realm UI, select "Authentication" from the lefthand menu, followed by "Authentication Providers." Click the "Edit" button for "Email/Password":
Enable username password authentication
Enable the provider and select "Automatically confirm users" and "Run a password reset function." Select "New function" and save without making any edits:
Configure authentication
Don't forget to click on "REVIEW & DEPLOY" whenever you've made a change to the back end Realm app.



Document on User Registration

When a new user registers, we need to create a User document in Atlas that will eventually synchronize with a User object in the iOS app. Realm provides authentication triggers that can automate this.
Select "Triggers" and then click on "Add a Trigger":
Add auth trigger
Set the "Trigger Type" to "Authentication," provide a name, set the "Action Type" to "Create" (user registration), set the "Event Type" to "Function," and then select "New Function":
Configure auth trigger
Name the function createNewUserDocument and add the code for the function:
Note that we set the partition to user=<id of the user>, which matches the partition used when the iOS app opens the User realm.
"Save" then "REVIEW & DEPLOY."

Define Realm Schema

Refer to Building a Mobile Chat App Using Realm – Data Architecture to understand more about the app's schema and partitioning rules. This article skips the analysis phase and just configures the Realm schema.
Browse to the "Rules" section in the Realm UI and click on "Add Collection." Set "Database Name" to RChat and "Collection Name" to User. We won't be accessing the User collection directly through Realm, so don't select a "Permissions Template." Click "Add Collection":
Add user collection
At this point, I'll stop reminding you to click "REVIEW & DEPLOY!"
Select "Schema," paste in this schema, and then click "SAVE":
Define Realm Schema
Repeat for the Chatster schema:
And for the ChatMessage collection:

Enable Realm Sync

Realm Sync is used to synchronize objects between instances of the iOS app (and we'll extend this app to also include Android). It also syncs those objects with Atlas collections. Note that there are three options to create a Realm schema:
  1. Manually code the schema as a JSON schema document.
  2. Derive the schema from existing data stored in Atlas. (We don't yet have any data and so this isn't an option here.)
  3. Derive the schema from the Realm objects used in the mobile app.
We've already specified the schema and so will stick to the first option.
Select "Sync" and then select your Atlas cluster. Set the "Partition Key" to the partition attribute (it appears in the list as it's already in the schema for all three collections), and the rules for whether a user can sync with a given partition:
Enable Realm Sync
The "Read" rule controls whether a user can establish one-way read-only sync relationship to the mobile app for a given user and partition. In this case, the rule delegates this to a Realm function named canReadPartition:
The "Write" rule delegates to the canWritePartition:
Once more, we've already seen those functions in Building a Mobile Chat App Using Realm – Data Architecture but I'll include the code here for completeness.
To create these functions, select "Functions" and click "Create New Function." Make sure you type the function name precisely, set "Authentication" to "System," and turn on the "Private" switch (which means it can't be called directly from external services such as our mobile app):
Define Realm Function

Linking User and Chatster Documents

As described in Building a Mobile Chat App Using Realm – Data Architecture, there are relationships between different User and Chatster documents. Now that we've defined the schemas and enabled Realm Sync, it's a convenient time to add the Realm function and database trigger to maintain those relationships.
Create a Realm function named userDocWrittenTo, set "Authentication" to "System," and make it private. This article is aiming to focus on the iOS app more than the back end Realm app, and so we won't delve into this code:
Set up a database trigger to execute the new function whenever anything in the User collection changes:
Add database trigger

Registering and Logging in From the iOS App

We've now created enough of the back end Realm app that mobile apps can now register new Realm users and use them to log into the app.
The app's top-level SwiftUI view is ContentView, which decides which sub-view to show based on whether our AppState environment object indicates that a user is logged in or not:
When first run, no user is logged in and so LoginView is displayed.
Note that AppState.loggedIn checks whether a user is currently logged into the Realm app:
The UI for LoginView contains cells to provide the user's email address and password, a radio button to indicate whether this is a new user, and a button to register or log in a user:
Login View
Clicking the button executes one of two functions:
signup makes an asynchronous call to the Realm SDK to register the new user. Through a Combine pipeline, signup receives an event when the registration completes, which triggers it to invoke the login function:
The login function uses the Realm SDK to log in the user asynchronously. If/when the Realm login succeeds, the Combine pipeline sends the Realm user to the chatsterLoginPublisher and loginPublisher publishers (recall that we've seen how those are handled within the AppState class):

Saving the User Profile

On being logged in for the first time, the user is presented with SetProfileView. (They can also return here later by clicking on their avatar.) This is a SwiftUI sheet where the user can set their profile and preferences by interacting with the UI and then clicking "Save User Profile":
Set profile view
When the view loads, the UI is populated with any existing profile information found in the User object in the AppState environment object:
As the user updates the UI elements, the Realm User object isn't changed. It's only when they click "Save User Profile" that we update the User object. Note that it uses the userRealm that was initialized when the user logged in to open a Realm write transaction before making the change:
Once saved to the local realm, Realm Sync copies changes made to the User object to the associated User document in Atlas.

List of Conversations

Once the user has logged in and set up their profile information, they're presented with the ConversationListView:
ConversationListView displays a list of all the conversations that the user is currently a member of (initially none) by looping over conversations within their User Realm object:
At any time, another user can include you in a new group conversation. This view needs to reflect those changes as they happen:
New conversation
When the other user adds us to a conversation, our User document is updated automatically through the magic of Realm Sync and our Realm trigger; but we need to give SwiftUI a nudge to refresh the current view. We do that by registering for Realm notifications and updating the lastSync state variable on each change. We register for notifications when the view appears and deregister when it disappears:

Creating New Conversations

NewConversationView is another view that lets the user provide a number of details which are then saved to Realm when the "Save" button is tapped. What's new is that it uses Realm to search for all users that match a filter pattern:

Conversation Status

Conversation update
When the status of a conversation changes (users go online/offline or new messages are received), the card displaying the conversation details should update.
We already have a Realm function to set the presence status in Chatster documents/objects when users log on or off. All Chatster objects are readable by all users, and so ConversationCardContentsView can already take advantage of that information.
The conversation.unreadCount is part of the User object and so we need another Realm trigger to update that whenever a new chat message is posted to a conversation.
We add a new Realm function chatMessageChange that's configured as private and with "System" authentication (just like our other functions). This is the function code that will increment the unreadCount for all User documents for members of the conversation:
That function should be invoked by a new Realm database trigger (ChatMessageChange) to fire whenever a document is inserted into the RChat.ChatMessage collection.

Within the Chat Room

Chat message
ChatRoomView has a lot of similarities with ConversationListView, but with one fundamental difference. Each conversation/chat room has its own partition, and so when opening a conversation, you need to open a new realm and observe for changes in it:
Note that we only open a Conversation realm when the user opens the associated view because having too many realms open concurrently can exhaust resources. It's also important that we stop observing the realm by setting it to nil when leaving the view:
To send a message, all the app needs to do is to add the new chat message to Realm. Realm Sync will then copy it to Atlas, where it is then synced to the other users:


In this article, we've gone through the key steps you need to take when building a mobile app using Realm, including:
  • Managing the user lifecycle: registering, authenticating, logging in, and logging out.
  • Managing and storing user profile information.
  • Adding objects to Realm.
  • Performing searches on Realm data.
  • Syncing data between your mobile apps and with MongoDB Atlas.
  • Reacting to data changes synced from other devices.
  • Adding some back end magic using Realm triggers and functions.
There's a lot of code and functionality that hasn't been covered in this article, and so it's worth looking through the rest of the app to see how to use features such as these from a SwiftUI iOS app:
  • Location data
  • Maps
  • Camera and photo library
  • Actions when minimizing your app
  • Notifications
We wrote the iOS version of the app first, but we plan on adding an Android (Kotlin) version soon – keep checking the developer hub and the repo for updates.


If you have questions, please head to our developer community website where the MongoDB engineers and the MongoDB community will help you build your next big idea with MongoDB.

Facebook Icontwitter iconlinkedin icon
Rate this tutorial

Saving Data in Unity3D Using BinaryReader and BinaryWriter

Sep 07, 2022 | 12 min read

Realm-Swift Type Projections

May 09, 2022 | 4 min read

Saving Data in Unity3D Using Files

Sep 07, 2022 | 11 min read

Let’s Give Your Realm-Powered Ionic Web App the Native Treatment on iOS and Android!

Sep 16, 2022 | 7 min read
Table of Contents
  • Prerequisites