iOS SDK

Updated

The Swift package reads the strings you publish with Delivery (CDN) into an iOS or macOS app. A text fix reaches users without an App Store release. Reads are synchronous and never wait for the network: the app shows downloaded strings when it has them, then the ones bundled in the app. Requires iOS 15 or macOS 12, and has no dependencies.

Anything you publish is public – never put secrets in translations
Anyone who knows a distribution's URL can download its strings. Keep API keys, internal URLs and personal data out of every branch you publish.
Release status
The package is version 0.1.0 and is meant to be public, installed from the GitHub repository named below. If Swift Package Manager can't resolve it yet, it hasn't been published. This page describes the 0.1.0 API.

Before you start

Create a distribution under Project Settings → Delivery (CDN) and publish a release, as described in Delivery (CDN). The SDK needs the distribution's public ID, the 22-character part of its manifest URL. In the app, Copy SDK snippet on the distribution card has an iOS entry that fills it in.

Install

In Xcode, choose File → Add Package Dependencies… and enter https://github.com/Translatize/ota-swift. Or add it to Package.swift:

Package.swift
dependencies: [
    .package(url: "https://github.com/Translatize/ota-swift", from: "0.1.0"),
],
targets: [
    .target(name: "MyApp", dependencies: [
        .product(name: "TranslatizeOTA", package: "ota-swift"),
    ]),
]

Set it up

Create one instance and keep it for the life of the app.

App.swift
import TranslatizeOTA

let ota = TranslatizeOTA(
    distributionId: "YOUR_DISTRIBUTION_ID",
    cdnURL: URL(string: "https://cdn.translatize.com")!,
    bundled: ["en": ["home.title": "Welcome"]]
)

cdnURL and bundled are optional; cdnURL defaults to https://cdn.translatize.com. Options are listed below.

Read strings

Swift
let title = ota.string("home.title", language: "en")      // String?
let label = ota.localized("home.title", fallback: "Welcome")
  • string(_:language:) returns the value for exactly that language, or nil.
  • localized(_:fallback:) reads ota.language and returns fallback when no value exists. language starts as the device's first preferred language; you can pass your own to the initializer or set it at any time. A region falls back to its base language, so de-DE finds de.
  • Nested files read by dotted keys: {"home": {"title": "Hi"}} is home.title. Flat files read by their own keys. Keys whose value isn't a string are skipped.

Bundled strings

Bundled strings are flat, one dictionary per language. To load a JSON file you ship with the app, nested or flat:

Swift
func bundledStrings(_ language: String) -> [String: String] {
    guard let url = Bundle.main.url(forResource: language, withExtension: "json"),
          let data = try? Data(contentsOf: url) else { return [:] }
    return TranslatizeOTA.strings(fromJSON: data)
}

let ota = TranslatizeOTA(distributionId: "YOUR_DISTRIBUTION_ID", bundled: ["en": bundledStrings("en")])

Bundle your default language. Before the first download it is the only text you have. The reading order is the downloaded value first, then the bundled one, key by key – so a key that is new in an app update isn't lost to an older downloaded release.

Refresh and updates

Reading a language starts a background check when its cached copy is older than minRefreshMs (5 minutes by default). The check loads the manifest with If-None-Match and downloads a language file only when its hash changed. At most one check per language starts from reads in that time, failed checks included.

Swift
let subscription = ota.onUpdate { language, strings in
    reloadInterface()
}

// check now, e.g. to wait for the first download
await ota.refresh()
  • onUpdate listeners run on the main actor, only when new strings were stored. Keep the returned token: subscription.cancel() or releasing it unsubscribes.
  • await ota.refresh() checks now, for the current language and every language read so far, ignoring minRefreshMs. It returns once new strings are in place and listeners have run, so it is also how you wait for a first download. Languages you haven't read yet are not downloaded, because every CDN request counts towards your delivery volume.

SwiftUI

OTAStrings is an ObservableObject that re-renders views when new strings arrive:

Swift
@main
struct ExampleApp: App {
    @StateObject private var strings = OTAStrings(ota)

    var body: some Scene {
        WindowGroup {
            ContentView().environmentObject(strings)
        }
    }
}

struct ContentView: View {
    @EnvironmentObject private var strings: OTAStrings

    var body: some View {
        Text(strings.localized("home.title", fallback: "Welcome"))
    }
}

On iOS 17 and macOS 14 and up you can use OTAObservableStrings instead, which is @Observable:

Swift
@State private var strings = OTAObservableStrings(ota)

Both have the same string(_:language:), localized(_:fallback:) and language. The instance behind them is strings.ota.

Placeholders stay as stored

Values come back exactly as they are stored. The SDK doesn't parse, escape or fill placeholders and has no formatting engine, so your app keeps its own format: %@, %1$@, ICU or anything else. Format the result yourself:

Swift
let template = ota.localized("cart.items", fallback: "%d items")
let text = String(format: template, count)

A wrong specifier in a published string can crash String(format:), so leave the placeholder checks in Quality checks on for strings you format.

What's cached, and where

The SDK writes to Caches/translatize-ota/, one file per distribution and language. Each file holds the hash, the strings and the time of the fetch. The last manifest and its ETag are kept too.

  • Writes are atomic. A damaged file is ignored and replaced.
  • The system may clear the Caches directory when space is low. The app then starts from bundled strings again and downloads the current release.
  • Bundle is never swizzled, so NSLocalizedString and your .strings files are unaffected. Call the SDK where you want downloaded text.
  • The first read of a language reads its cache file from disk once, so the first frame can already show downloaded strings.

When the CDN says no, or isn't there

Nothing throws into your app. On every failure below the strings you have stay in place.

CaseWhat happens
Offline, timeout, bad fileThe check ends and you keep the strings you had.
Hash mismatchEvery file is verified against the sha256 in the manifest. A file that doesn't match is thrown away.
429The SDK makes no requests until Retry-After has passed (an hour if the header is missing, a day at most) and keeps serving what it has.
404The distribution is disabled or unknown. The SDK keeps serving what it has and stops calling the CDN until the next launch.
Invalid distribution IDCached and bundled strings are served and the CDN is never called.

The pause after a 429 and the stop after a 404 last for the running app only. See When the limit is reached for what causes them, and Requests and blocks for how requests are counted.

Options

OptionDefaultWhat it does
distributionIdrequiredThe public ID from Delivery (CDN) in your project settings.
cdnURLhttps://cdn.translatize.comWhere the SDK fetches from.
bundled[:]Flat strings per language.
languagedevice languageWhat localized reads.
minRefreshMs300000 (5 minutes)Cached data younger than this is not re-checked. The lowest value is 1 second.
timeoutMs3000Per request.
cacheDirectoryCaches/translatize-otaWhere the cache lives.
transporta private URLSessionAnything that conforms to OTATransport.

If you pass your own URLSession, turn off its URL cache, or it can answer the ETag check itself.

Using Android or Flutter? See the Android SDK and the Flutter SDK.