Build Your First iOS Mobile App Using Realm, SwiftUI, & Combine
Rate this tutorial
I'm relatively new to building iOS apps (a little over a year's experience), and so I prefer using the latest technologies that make me a more productive developer. That means my preferred app stack looks like this:
This article was updated in July 2021 to replace
objc
and dynamic
with the @Persisted
annotation that was introduced in Realm-Cocoa 10.10.0.In 🔥 | Out ❄️ |
---|---|
Swift | Objective C |
SwiftUI | UIKit |
Combine | RxSwift |
Realm | Core Data |
MongoDB Realm Sync (where needed) | Home-baked cross-platform data sync |
This article presents a simple task management app that I built on that stack. To continue my theme on being productive (lazy), I've borrowed heavily (stolen) from MongoDB's official iOS Swift tutorial:
- I've refactored the original front end, adding Combine for event management, and replacing the UIKit ViewControllers with Swift views.
- The back end Realm app is entirely unchanged. Note that once you've stood up this back end, then this app can share its data with the equivalent Android, React/JavaScript, and Node.js apps with no changes.
I'm going to focus here on the iOS app. Check the official tutorial if you want to understand how the back end works.
I'm lucky that I don't have to support an existing customer base that's running on old versions of iOS, and so I can take advantage of the latest language, operating system, and SDK features:
- A Mac (sorry Windows and Linux users)
- iOS14+ / XCode 12.2+
- It would be pretty easy to port the app back to iOS13, but iOS14 makes SwiftUI more of a first-class citizen (though there are still times when a more complex app would need to break out into UIKit code—e.g., if you wanted to access the device's camera).
- Apple introduced SwiftUI and Combine in iOS13, and so you'd be better sticking with the original tutorial if you need to support iOS12 or earlier.
- Realm Cocoa 10 adds support for Combine and the ability to "Freeze" Realm Objects, making it simpler and safer to embed them directly within SwiftUI views.
I always prefer to build and run an app before being presented with code snippets; these are the steps:
- If you don't already have Xcode 12 installed, install it through the Apple App Store.
- Set up your back end Realm app. Make a note of the ID:
- Download the iOS app, install dependencies, and open the workspace in Xcode:
- Within Xcode, edit
task-tracker-swiftui/task_tracker_swiftuiApp.swift
and set the Realm application ID to the value you noted in Step 2: - In Xcode, select an iOS simulator:
Select an iOS simulator in Xcode - Build and run the app using
⌘-R
. - Go ahead and play with the app:
Demo of the app in an iOS simulator
Usually, when people start explaining SwiftUI, they begin with, "You know how you do X with UIKit? With SwiftUI, you do Y instead." But, I'm not going to assume that you're an experienced UIKit developer.
If you built and ran the app, you've already seen the "root" of the app in
swiftui_realmApp.swift
:app
is the Realm application that will be used by our iOS app to store and retrieve data stored in Realm.SwiftUI works with views, typically embedding many views within other views (a recent iOS app I worked on has over 500 views), and you always start with a top-level view for the app—in this case,
ContentView
.Individual views contain their own state (e.g., the details of the task that's currently being edited, or whether a pop-up sheet should be displayed), but we store any app-wide state in the
state
variable. @ObservedObject
is a SwiftUI annotation to indicate that a view should be refreshed whenever particular attributes within an object change. We pass state to ContentView
as an environmentOject
so that any of the app's views can access it.Like other declarative, state-driven frameworks (e.g., React or Vue.js), components/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:We use
shouldIndicateActivity
to control whether a "working on it" view should be displayed while the app is busy. error is set whenever we want to display an error message. Both of these variables are annotated with @Published
to indicate that referencing views should be refreshed when their values change.user
represents the Realm user that's currently logged into the app.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
, logoutPublisher
, and userRealmPublisher
are publishers to handle logging in, logging out, and opening a Realm for a user.As an example, when an event is sent to
loginPublisher
to indicate that the login process has completed, Combine will run this pipeline:The pipeline receives the freshly-logged-in Realm user.
The
receive(on: DispatchQueue.main)
stage specifies that the next stage in the pipeline should run in the main thread (because it will update the UI).The Realm user is passed to the
flatMap
stage which:- Updates the UI to show that the app is busy.
- Opens a Realm for this user (requesting Objects where the partition matches the string
"user=\(user.id"
). - Passes a publisher for the opening of the Realm to the next stage.
The
.subscribe
stage subscribes the userRealmPublisher
to outputs from the publisher it receives from the previous stage. In that way, a pipeline associated with the userRealmPublisher
publisher can react to an event indicating when the Realm has been opened.The
.store
stage stores the publisher in the cancellables
array so that it isn't removed when the init()
function completes.You'll find the Realm object model in the
Model
group in the Xcode workspace. These are the objects used in the iOS app and synced to MongoDB Atlas in the back end.The
User
class represents application users. It inherits from Object
which is a class in the Realm SDK and allows instances of the class to be stored in Realm:Note that instances of classes that inherit from
Object
can be used as @ObservedObjects
without inheriting from ObservableObject
or annotating attributes with @Public
.Summary of the attributes:
_id
uniquely identifies aUser
object. We set it to be the Realm primary key._partition
is used as the partition key, which can be used by the app to filter whichUser
Objects
it wants to access.name
is the username (email address).membersOf
is a Realm List of projects that the user can access. (It always contains its own project, but it may also include other users' projects if those users have added this user to their teams.)
The elements in
memberOf
are instances of the Project
class. Project
inherits from EmbeddedObject
which means that instances of Project
can be embedded within other Realm Objects
:Summary of the attributes:
name
is the project's name.partition
is a string taking the form"project=project-name"
whereproject-name
is the_id
of the project's owner.
Individual tasks are represented by the
Task
class:Summary of the attributes:
_id
uniquely identifies aTask
object. We set it to be the Realm primary key._partition
is used as the partition key, which can be used by the app to filter whichTask
Objects
it wants to access. It takes the form"project=project-id"
.name
is the task's title.status
takes on the value "Open", "InProgress", or "Complete".
We want app users to only be able to access the tasks from their own project (or the projects of other users who have added them to their team). Our users need to see their tasks when they restart the app or run it on a different device. Realm's username/password authentication is a simple way to enable this.
Recall that our top-level SwiftUI view is
ContentView
(task-tracker-swiftui/Views/ContentView.swift
). ContentView
selects whether to show the LoginView
or ProjectsView
view based on whether a user is already logged into Realm:Note that
ContentView
also renders the state.error
message and the ProgressView
views. These will kick in whenever a sub-view updates state.LoginView
(task-tracker-swiftui/Views/User Accounts/LoginView.swift
) presents a simple form for existing app users to log in:
When the user taps "Log In", the
login
function is executed:login
calls app.login
(app
is the Realm app that we create when the app starts) which returns a Combine publisher. The results from the publisher are passed to a Combine pipeline which updates the UI and sends the resulting Realm user to loginPublisher
, which can then complete the process.If it's a first-time user, then they tap "Register new user" to be taken to
SignupView
which registers a new user with Realm (app.emailPasswordAuth.registerUser
) before popping back to loginView
(self.presentationMode.wrappedValue.dismiss()
):To complete the user lifecycle,
LogoutButton
logs them out from Realm and then sends an event to logoutPublisher
:
After logging in, the user is shown
ProjectsView
(task-tracker-swiftui/Views/Projects & Tasks/ProjectsView.swift
) which displays a list of projects that they're a member of:Recall that
state.user
is assigned the data retrieved from Realm when the pipeline associated with userRealmPublisher
processes the event forwarded from the login pipeline:Each project in the list is a button that invokes
showTasks(project)
:showTasks
opens a new Realm and then sets up the variables which are passed to TasksView
in body (note that the NavigationLink
is automatically followed when showingTasks
is set to true
):
TasksView
(task-tracker-swiftui/Views/Projects & Tasks/TasksView.swift
) presents a list of the tasks within the selected project:Tasks can be removed from the projects by other instances of the application or directly from Atlas in the back end. SwiftUI tends to crash if an item is removed from a list which is bound to the UI, and so we use Realm's "freeze" feature to isolate the UI from those changes:
However,
TaskView
can make changes to a task, and so we need to "unfreeze" Task
Objects
before passing them in:When the view loads, we must fetch the latest list of tasks in the project. We want to refresh the view in the UI whenever the app observes a change in the list of tasks. The
loadData
function fetches the initial list, and then observes the Realm and updates the lastUpdate
field on any changes (which triggers a view refresh):To conserve resources, we release the refresh token when leaving this view:
We delete a task when the user swipes it to the left:

TaskView
(task-tracker-swiftui/Views/Projects & Tasks/TaskView.swift
) is responsible for rendering a Task
Object
; optionally adding an image and format based on the task status:The task in the UI is a button that exposes
UpdateTaskView
when tapped. That view doesn't cover any new ground, and so I won't dig into it here.
A user can add others to their team; all team members can view and edit tasks in the user's project. For the logged-in user to add another member to their team, they need to update that user's
User
Object
. This isn't allowed by the Realm Rules in the back end app. Instead, we make use of Realm Functions that have been configured in the back end to make these changes securely.TeamsView
(task-tracker-swiftui/Views/Teams/TeamsView.swift
) presents a list of all the user's teammates:We invoke a Realm Function to fetch the list of team members, when this view is opened (
.onAppear
) through the fetchTeamMembers
function:Swiping left removes a team member using another Realm Function:
Tapping on the "+" button opens up the
AddTeamMemberView
sheet/modal, but no new concepts are used there, and so I'll skip it here.Our app relies on the latest features in the Realm-Cocoa SDK (notably Combine and freezing objects) to bind the model directly to our SwiftUI views. You may have noticed that we don't have a view model.
We use Realm's username/password functionality and Realm Sync to ensure that each user can work with all of their tasks from any device.
You've seen how the front end app can delegate work to the back end app using Realm Functions. In this case, it was to securely work around the data access rules for the
User
object; other use-cases for Realm Functions are:- Securely access other network services without exposing credentials in the front end app.
- Complex data wrangling using the MongoDB Aggregation Framework.
- We've used Apple's Combine framework to handle asynchronous events, such as performing follow-on actions once the back end confirms that a user has been authenticated and logged in.
This iOS app reuses the back end Realm application from the official MongoDB Realm tutorials. This demonstrates how the same data and back end logic can be shared between apps running on iOS, Android, web, Node.js...
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.