DEV Community

Cover image for Free currency rates in SwiftUI without an API key: a fallback chain with an offline cache
Safak AVCI
Safak AVCI

Posted on Fully Autonomous

Free currency rates in SwiftUI without an API key: a fallback chain with an offline cache

A currency converter is only as reliable as its exchange rate API, and free APIs are not very reliable.

Free tiers have monthly limits. Some need a key you have to ship inside the app. Some go down for an afternoon. When that happens, a converter shows a spinner, then an error, and the user deletes the app.

Here is the pattern I use in Swap+, my SwiftUI currency and VAT app with 154 currencies. It has three layers:

  1. A chain of providers, tried in order, so one failing source is invisible to the user.
  2. A short-lived cache, so we don't hit any API more than we need to.
  3. An offline floor: the last good rates, or bundled defaults, so the app always opens with numbers.

1. Describe each provider as data

Instead of hard-coding one API, each source is a small config value with a priority:

struct APIConfig {
    let name: String
    let baseURL: String
    let apiKey: String      // empty for free, keyless sources
    let priority: Int       // lower runs first
    var requiresKey = false // true for paid providers
}
Enter fullscreen mode Exit fullscreen mode

The keyless sources are the interesting part. These worked without any key when I built the app (check each one's terms before you rely on it):

Source Endpoint Notes
Frankfurter api.frankfurter.app ECB data, about 30 major currencies
FloatRates floatrates.com Daily JSON feeds per base currency
fawazahmed0 currency-api cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/usd.json Served from a CDN, 150+ currencies
Open ER-API open.er-api.com/v6/latest/USD Free; read its attribution terms
ExchangeRate-API v4 api.exchangerate-api.com/v4/latest/USD Open access endpoint

Keyed providers (Fixer, CurrencyLayer, Open Exchange Rates and others) can sit at the top of the list for paid users. With no key, they fail quickly and the chain moves on. If you prefer, filter them out up front:

let chain = apiConfigs
    .filter { !$0.requiresKey || !$0.apiKey.isEmpty }
    .sorted { $0.priority < $1.priority }
Enter fullscreen mode Exit fullscreen mode

2. Normalise every response to one shape

Each API returns a different JSON layout. The rest of the app should never know that. Every fetcher returns the same thing: [String: Double], rates against USD, with upper-case codes.

The CDN source is a good example. It returns lower-case keys nested under the base currency:

// { "date": "2026-11-23", "usd": { "eur": 0.92, "gbp": 0.79, ... } }
struct FawazResponse: Decodable {
    let date: String
    let usd: [String: Double]
}

func fetchFawaz(_ config: APIConfig) async throws -> [String: Double] {
    var request = URLRequest(url: URL(string: "\(config.baseURL)/usd.json")!)
    request.timeoutInterval = 5          // fail fast, the chain has more options

    let (data, response) = try await URLSession.shared.data(for: request)
    guard (response as? HTTPURLResponse)?.statusCode == 200 else {
        throw APIError.invalidResponse
    }
    let decoded = try JSONDecoder().decode(FawazResponse.self, from: data)

    var rates = ["USD": 1.0]
    for (code, rate) in decoded.usd { rates[code.uppercased()] = rate }
    return rates
}
Enter fullscreen mode Exit fullscreen mode

The five-second timeout matters more than it looks. With the default 60 seconds, a single slow provider would freeze the whole chain.

3. Walk the chain

The fetch loop is short. Try each provider in order and stop at the first one that returns a non-empty result:

func fetchRates(forceRefresh: Bool = false) async {
    if !forceRefresh && isCacheValid() { return }

    // Don't wait for timeouts when we already know there is no network.
    guard NetworkMonitor.shared.isConnected else {
        await MainActor.run { useCachedOrDefaultRates() }
        return
    }

    for config in apiConfigs.sorted(by: { $0.priority < $1.priority }) {
        if let rates = try? await fetch(config), !rates.isEmpty {
            await MainActor.run {
                self.rates = rates
                self.lastUpdateTime = Date()
            }
            saveCachedRates()
            return
        }
    }

    // Every provider failed: keep what we have.
    await MainActor.run { useCachedOrDefaultRates() }
}
Enter fullscreen mode Exit fullscreen mode

NetworkMonitor is a tiny NWPathMonitor wrapper that publishes isConnected. Checking it first turns "airplane mode" from a long wait into an instant answer.

4. Cache, then fall back to a floor

The cache is deliberately simple: the rates dictionary and a timestamp in UserDefaults.

private let cacheExpiryMinutes = 10.0

func isCacheValid() -> Bool {
    guard let time = lastUpdateTime else { return false }
    return Date().timeIntervalSince(time) / 60 < cacheExpiryMinutes && !rates.isEmpty
}

func saveCachedRates() {
    if let data = try? JSONEncoder().encode(rates) {
        UserDefaults.standard.set(data, forKey: "cached_exchange_rates")
        UserDefaults.standard.set(lastUpdateTime, forKey: "cache_update_time")
    }
}
Enter fullscreen mode Exit fullscreen mode

Two things to note:

  • The cache is loaded in init. The first screen shows the last known rates immediately, before any network call starts.
  • There is a bundled floor. A small dictionary of default rates for about 20 major currencies ships with the app. On a fresh install with no network, the user still gets an approximate answer, plus a clear "using offline rates" message instead of an empty screen.

Ten minutes is a good expiry for a consumer converter: opening the app several times within ten minutes causes one request, not several.

5. Tell the user what they are looking at

Silent fallbacks are good engineering and bad UX if the user doesn't know. The service publishes two extra values:

@Published var isOfflineMode = false
@Published var error: String?   // e.g. "Could not update rates. Using last known rates."
Enter fullscreen mode Exit fullscreen mode

The converter screen shows when the rates were last updated, and a short message such as "Could not update rates. Using last known rates." when it falls back. Nobody minds slightly old rates. People mind not knowing.

Bonus: switching language inside the app

Swap+ ships 88 languages, and users can pick one inside the app, independent of the system language. The core is an ObservableObject that remembers the choice:

final class TranslationManager: ObservableObject {
    static let shared = TranslationManager()
    @Published private var current: LanguageCode

    func setLanguage(_ language: LanguageCode) {
        current = language
        UserDefaults.standard.set(language.rawValue, forKey: "AppLanguage")
        NotificationCenter.default.post(name: .languageChanged, object: nil)
    }

    func translate(_ key: String) -> String {
        translations[current.rawValue]?[key]   // chosen language
            ?? translations["en"]?[key]        // English fallback
            ?? key                             // never show an empty label
    }
}
Enter fullscreen mode Exit fullscreen mode

If the user never picked a language, it follows the system, and falls back from pt-BR to pt to English. The same "always have a fallback" idea as the rates.

Wrapping up

The pattern is small: providers as data, one normalised shape, a short timeout, a chain, a cache and a floor. It needs no API key and costs nothing to run.

If you want to see it in a real, shipped app, the full SwiftUI source code of Swap+ (currency converter, VAT for 197 countries, 88 languages, AdMob with ATT) is available here: Currency & VAT Calculator – SwiftUI source code. It opens and runs in Xcode with no accounts.

Questions about any part of this? Ask in the comments.

Top comments (2)

Collapse
 
furqan_ashraf profile image
Furqan Ashraf •

The 5-second timeout is the most useful line in this post. Most people leave it at the 60-second default and only notice when one provider hangs.

One thing I'd add to the cache: store which provider answered and the date that provider reports, not only lastUpdateTime = Date(). Right now "last updated" is when the app fetched, but the sources publish on different schedules. Frankfurter is ECB data (as you note in the table), and the CDN feed has its own date field. If the chain drops from one source to the next, the numbers can jump a little with nothing changing in the market, and the user sees a fresh timestamp on data that may be a day old. Showing "rates as of " keeps the honest-UX point from section 5 true.

If you do put a keyed provider at the top, check how it encodes the numbers before reusing your [String: Double] decoders. The APIFreaks Exchange Rate API (APIFreaks.com/api/currency-rate), for example, returns rates as strings, so it needs its own small fetcher:

// GET https://api.apifreaks.com/v1.0/currency/rates/latest?symbols=EUR,GBP,TRY&updates=10m
// header: X-apiKey: <key>
// { "date": "2026-07-27 12:01:00+00", "base": "USD", "rates": { "EUR": "0.878156", ... } }
struct AFResponse: Decodable {
    let date: String
    let base: String
    let rates: [String: String]
}

func fetchAF(_ config: APIConfig) async throws -> [String: Double] {
    var request = URLRequest(url: URL(string: "\(config.baseURL)/currency/rates/latest?updates=10m")!)
    request.setValue(config.apiKey, forHTTPHeaderField: "X-apiKey")
    request.timeoutInterval = 5
    let (data, response) = try await URLSession.shared.data(for: request)
    guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw APIError.invalidResponse }
    let decoded = try JSONDecoder().decode(AFResponse.self, from: data)
    var rates = ["USD": 1.0]
    for (code, value) in decoded.rates {
        if let v = Double(value) { rates[code.uppercased()] = v }
    }
    return rates
}
Enter fullscreen mode Exit fullscreen mode

The updates=10m value matches your 10-minute cache. It also has a free signup tier (10,000 credits), and it's billed only on successful responses, which works well with a chain that fails over quickly. One caveat: as with any keyed source, put it behind a small proxy rather than in the app binary, for the reason you gave at the start of the post.

Collapse
 
safak_avci_40a85e276c10b5 profile image
Safak AVCI •

Thanks, that's a great point. You're right that "last updated" is really "last fetched": if the chain falls back from the CDN feed to Frankfurter, the timestamp looks fresh while the ECB data may be from the previous working day. Storing the provider's own date next to the rates and showing "rates as of ..." is a small change that keeps the UI honest, so I'll add it. And agreed on keyed providers: they belong behind a small proxy, not in the app binary.