EventGet 50% off your ticket to MongoDB.local NYC on May 2. Use code Web50!Learn more >>
MongoDB Developer
Swift
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Languageschevron-right
Swiftchevron-right

Build Offline-First Mobile Apps by Caching API Results in Realm

Andrew Morgan11 min read • Published Sep 13, 2021 • Updated Mar 06, 2023
iOSMobileRealmSwift
Facebook Icontwitter iconlinkedin icon
Rate this code example
star-empty
star-empty
star-empty
star-empty
star-empty

Introduction

When building a mobile app, there's a good chance that you want it to pull in data from a cloud service—whether from your own or from a third party. While other technologies are growing (e.g., GraphQL and MongoDB Realm Sync), REST APIs are still prevalent.
It's easy to make a call to a REST API endpoint from your mobile app, but what happens when you lose network connectivity? What if you want to slice and dice that data after you've received it? How many times will your app have to fetch the same data (consuming data bandwidth and battery capacity each time)? How will your users react to a sluggish app that's forever fetching data over the internet?
By caching the data from API calls in Realm, the data is always available to your app. This leads to higher availability, faster response times, and reduced network and battery consumption.
This article shows how the RCurrency mobile app fetches exchange rate data from a public API, and then caches it in Realm for always-on, local access.

Is Using the API from Your Mobile App the Best Approach?

This app only reads data through the API. Writing an offline-first app that needs to reliably update cloud data via an API is a far more complex affair. If you need to update cloud data when offline, then I'd strongly recommend you consider MongoDB Realm Sync.
Many APIs throttle your request rate or charge per request. That can lead to issues as your user base grows. A more scalable approach is to have your backend Realm app fetch the data from the API and store it in Atlas. Realm Sync then makes that data available locally on every user's mobile device—without the need for any additional API calls.

Prerequisites

The RCurrency Mobile App

The RCurrency app is a simple exchange rate app. It's intended for uses such as converting currencies when traveling.
You choose a base currency and a list of other currencies you want to convert between.
When opened for the first time, RCurrency uses a REST API to retrieve exchange rates, and stores the data in Realm. From that point on, the app uses the data that's stored in Realm. Even if you force-close the app and reopen it, it uses the local data.
If the stored rates are older than today, the app will fetch the latest rates from the API and replace the Realm data.
The app supports pull-to-refresh to fetch and store the latest exchange rates from the API.
You can alter the amount of any currency, and the amounts for all other currencies are instantly recalculated.
Animation of the RCurrency app running on an iPhone. Includes the user selecting currencies, changing amounts and observing the amounts changing for other currencies

The REST API

I'm using the API provided by exchangerate.host. The API is a free service that provides a simple API to fetch currency exchange rates.
One of the reasons I picked this API is that it doesn't require you to register and then manage access keys/tokens. It's not rocket science to handle that complexity, but I wanted this app to focus on when to fetch data, and what to do once you receive it.
The app uses a single endpoint (where you can replace USD and EUR with the currencies you want to convert between):
The endpoint responds with a JSON document:
Note that the exchange rate for each currency is only updated once every 24 hours. That's fine for our app that's helping you decide whether you can afford that baseball cap when you're on vacation. If you're a currency day-trader, then you should look elsewhere.

The RCurrency App Implementation

Data Model

JSON is the language of APIs. That's great news as most modern programming languages (including Swift) make it super easy to convert between JSON strings and native objects.
The app stores the results from the API query in objects of type Rate. To make it as simple as possible to receive and store the results, I made the Rate class match the JSON format of the API results:
Note that only the fields annotated with @Persisted will be stored in Realm.
Swift can automatically convert between Rate objects and the JSON strings returned by the API because we make the class comply with the Codable protocol.
There are two other top-level classes used by the app.
Symbols stores all of the supported currency symbols. In the app, the list is bootstrapped from a fixed list. For future-proofing, it would be better to fetch them from an API:
UserSymbols is used to store the user's chosen base currency and the list of currencies they'd like to see exchange rates for:
An instance of UserSymbols is stored in Realm so that the user gets the same list whenever they open the app.
Rate

Data Lifecycle

This flowchart shows how the exchange rate for a single currency (represented by the symbol string) is managed when the CurrencyRowContainerView is used to render data for that currency:
Flowchart showing how the app fetches data from the API and stored in in Realm. The mobile app's UI always renders what's stored in MongoDB. The following sections will describe each block in the flow diagram.
Note that the actual behavior is a little more subtle than the diagram suggests. SwiftUI ties the Realm data to the UI. If stage #2 finds the data in Realm, then it will immediately get displayed in the view (stage #8). The code will then make the extra checks and refresh the Realm data if needed. If and when the Realm data is updated, SwiftUI will automatically refresh the UI to render it.
Let's look at each of those steps in turn.

#1

CurrencyContainerView

loaded for currency represented by

symbol
CurrencyListContainerView iterates over each of the currencies that the user has selected. For each currency, it creates a CurrencyRowContainerView and passes in strings representing the base currency (baseSymbol) and the currency we want an exchange rate for (symbol):

#2

rate

= FetchFromRealm(

symbol

)

CurrencyRowContainerView then uses the @ObservedResults property wrapper to query all Rate objects that are already stored in Realm:
The view then filters those results to find one for the requested baseSymbol/symbol pair:

#3

rate

found?

The view checks whether rate is set or not (i.e., whether a matching object was found in Realm). If rate is set, then it's passed to CurrencyRowDataView to render the details (step #8). If rate is nil, then a placeholder "Loading Data..." TextView is rendered, and loadData is called to fetch the data using the API (step #4-3):

#4-3 Fetch

rate

from API — No matching object found in Realm

The API URL is formed by inserting the base currency (baseSymbol) and the target currency (symbol) into a template string. loadData then sends the request to the API endpoint and handles the response:

#5-3 StoreInRealm(

rate

) — No matching object found in Realm

Rate objects stored in Realm are displayed in our SwiftUI views. Any data changes that impact the UI must be done on the main thread. When the API endpoint sends back results, our code receives them in a callback thread, and so we must use DispatchQueue to run our closure in the main thread so that we can add the resulting Rate object to Realm:
Notice how simple it is to convert the JSON response into a Realm Rate object and store it in our local realm!

#6 Refresh Requested?

RCurrency includes a pull-to-refresh feature which will fetch fresh exchange rate data for each of the user's currency symbols. We add the refresh functionality by appending the .refreshable modifier to the List of rates in CurrencyListContainerView:
refreshAll sets the refreshNeeded variable to true, waits a second to allow SwiftUI to react to the change, and then sets it back to false:
refreshNeeded is passed to each instance of CurrencyRowContainerView:
CurrencyRowContainerView checks refreshNeeded. If true, it displays a temporary refresh image and invokes refreshData (step #4-6):

#4-6 Fetch

rate

from API — Refresh requested

refreshData fetches the data in exactly the same way as loadData in step #4-3:
The difference is that in this case, there may already be a Rate object in Realm for this currency pair, and so the results are handled differently...

#5-6 StoreInRealm(

rate

) — Refresh requested

If the Rate object for this currency pair had been found in Realm, then we reference it with existingRate. existingRate is then updated with the API results:

#7

rate

stale?

The exchange rates available through the API are updated daily. The date that the rate applies to is included in the API response, and it’s stored in the Realm Rate object. When displaying the exchange rate data, CurrencyRowDataView invokes loadData:
loadData checks that the existing Realm Rate object applies to today. If not, then it will refresh the data (stage 4-7):
isToday is a Rate method to check whether the stored data matches the current date:

#4-7 Fetch

rate

from API —

rate

stale

By now, the code to fetch the data from the API should be familiar:

#5-7 StoreInRealm(

rate

) —

rate

stale

loadData copies the new date and exchange rate (result) to the stored Realm Rate object:

#8 View rendered with

rate
CurrencyRowView receives the raw exchange rate data, and the amount to convert. It’s responsible for calculating and rendering the results:
Screen capture showing the row for a single currency. In this case it shows the US flag, the "USD" symbol and the amount (3.23...)
The number shown in this view is part of a TextField, which the user can overwrite:
When the user overwrites the number, the onChange function is called which recalculates baseValue (the value of the base currency that the user wants to convert):
As baseValue was passed in as a binding, the new value percolates up the view hierarchy, and all of the currency values are updated. As the exchange rates are held in Realm, all of the currency values are recalculated without needing to use the API:
Animation showing the app running on an iPhone. When the user changes the amount for 1 currency, the amounts for all of the others changes immediately

Conclusion

REST APIs let your mobile apps act on a vast variety of cloud data. The downside is that APIs can't help you when you don't have access to the internet. They can also make your app seem sluggish, and your users may get frustrated when they have to wait for data to be downloaded.
A common solution is to use Realm to cache data from the API so that it's always available and can be accessed locally in an instant.
This article has shown you a typical data lifecycle that you can reuse in your own apps. You've also seen how easy it is to store the JSON results from an API call in your Realm database:
We've focussed on using a read-only API. Things get complicated very quickly when your app starts modifying data through the API. What should your app do when your device is offline?
  • Don't allow users to do anything that requires an update?
  • Allow local updates and maintain a list of changes that you iterate through when back online?
    • Will some changes you accept from the user have to be backed out once back online and you discover conflicting changes from other users?
If you need to modify data that's accessed by other users or devices, consider MongoDB Realm Sync as an alternative to accessing APIs directly from your app. It will save you thousands of lines of tricky code!
The API you're using may throttle access or charge per request. You can create a backend MongoDB Realm app to fetch the data from the API just once, and then use Realm Sync to handle the fan-out to all instances of your mobile app.
If you have any questions or comments on this post (or anything else Realm-related), then please raise them on our community forum. To keep up with the latest Realm news, follow @realm on Twitter and join the Realm global community.

Facebook Icontwitter iconlinkedin icon
Rate this code example
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Code Example

Adapting Apple's Scrumdinger SwiftUI Tutorial App to Use Realm


Sep 23, 2022 | 6 min read
Tutorial

Push Notifications Using Atlas App Services & iOS Realm SDK


Jul 19, 2022 | 8 min read
Tutorial

Authentication for Your iOS Apps with Apple Sign-in and Atlas App Services


Jul 13, 2023 | 6 min read
Tutorial

Authentication for Your iOS Apps with Atlas App Services


Oct 28, 2022 | 8 min read
Technologies Used
Languages
Technologies
Products
Table of Contents