Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions ios-sdk/about.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Tolgee iOS (and macOS) SDK makes it possible to deliver new translations from yo

- __Avoid releases for copy changes__: Ship translation fixes and new languages without a new app build.
- __Faster iteration__: Product/localization teams can push improvements instantly and validate in production.
- __Typed keys__: Generate a typed key for every key in your String Catalogs, so a typo in a key or a wrong argument fails the build.
- __SwiftUI support__: You can still use features such as overwriting locales for your SwiftUI previews.
- __Language Overwrite__: Change the app language at runtime, independent of the system language.
- __Resilient by default__: Works offline with caching and resource fallbacks; fewer blank strings.
Expand Down Expand Up @@ -42,6 +43,7 @@ The SDK currently supports iOS 16.0+ and macOS 13.0+ with integration via Swift
## Get started

- __Installation__: Install and configure the SDK — [Installation](./get_started.mdx)
- __Typed keys__: Generate typed keys from your String Catalogs and catch wrong keys at build time — [Typed keys](./typed_keys.mdx)
- __SwiftUI compatibility__: Learn how Tolgee iOS SDK works with your SwiftUI code — [SwiftUI](./swiftui.mdx)
- __NSLocalizedString swizzling__: Learn how to achieve zero config integration by enabling method swizzling — [Swizzling](swizzling.mdx)
- __Advanced usage__: Tips and tricks for debugging and using the SDK with advanced codebases — [Advanced usage](./advanced.mdx)
Expand Down
44 changes: 31 additions & 13 deletions ios-sdk/advanced.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ description: Tips and tricks for debugging and using the SDK with advanced codeb
image: /img/og-images/ios-sdk.png
---

### Language Overwrite
## Language Overwrite

You can override the default system language to display translations in a specific language. This is useful when implementing custom language switchers or when you want to force a specific language regardless of the device settings.

#### Setting Language During Initialization
### Setting Language During Initialization

You can set a custom language when initializing Tolgee:

Expand All @@ -28,7 +28,7 @@ Tolgee.shared.initialize(
)
```

#### Changing Language at Runtime
### Changing Language at Runtime

Use `setCustomLocale(_:language:)` to change the language dynamically:

Expand All @@ -46,7 +46,7 @@ try Tolgee.shared.setCustomLocale(
await Tolgee.shared.remoteFetch()
```

#### Resetting to System Language
### Resetting to System Language

To return to the device's system language:

Expand All @@ -55,7 +55,7 @@ try Tolgee.shared.setCustomLocale(.current)
await Tolgee.shared.remoteFetch()
```

#### Pre-fetching all available languages from the CDN
### Pre-fetching all available languages from the CDN

You can pre-fetch all languages supported by your app:

Expand All @@ -69,8 +69,10 @@ await withTaskGroup(of: Void.self) { group in
}
```

### Custom tables/namespaces
Tolgee iOS SDK supports loading of local translations from multiple local tables by providing the `table` parameter. When using `.xcstrings` files, the names of the tables match the names of your files without the extension. You do not need to provide the table name when loading strings stored in the default `Localizable.xcstrings` file.
## Custom tables/namespaces
Tolgee iOS SDK supports loading of local translations from multiple local tables. When using `.xcstrings` files, the names of the tables match the names of your files without the extension.

[Typed keys](./typed_keys.mdx) from tables other than the default `Localizable.xcstrings` are nested under the name of the table. With string keys, provide the `table` parameter. You do not need to provide the table name when loading strings stored in the default `Localizable.xcstrings` file.

To have the OTA updates working properly, make sure that you have enabled namespaces for your Tolgee project and that you have created namespaces matching the names of your local tables.

Expand All @@ -81,25 +83,41 @@ Tolgee.shared.initialize(
namespaces: ["common", "auth", "profile", "settings"]
)

// Use translations from specific namespaces
let commonGreeting = Tolgee.shared.translate("hello", table: "common")
// Typed keys from common.xcstrings are nested under the table name
let commonGreeting = Tolgee.shared.translate(.Common.hello)
// or for SwiftUI
TolgeeText("hello", table: "common")
TolgeeText(.Common.hello)

// With string keys, pass the table explicitly
let greeting = Tolgee.shared.translate("hello", table: "common")
TolgeeText("hello", tableName: "common")
```

## Custom bundles

You may have your strings resources stored in a dedicated XCFramework or a Swift Package.

```swift
let bundle: Bundle = ... // access the bundle
[Typed keys](./typed_keys.mdx) remember the bundle of their String Catalog, so keys generated in a package or a framework need no extra setup. Add the `TolgeeKeysPlugin` to the target that contains the String Catalog and use the keys inside that target.

```swift
// Use the SDK directly
let commonGreeting = Tolgee.shared.translate("hello", bundle: bundle)
let greeting = Tolgee.shared.translate(.hello)
// or for SwiftUI
TolgeeText(.hello)
```

With string keys, pass the bundle explicitly:

```swift
let bundle: Bundle = ... // access the bundle

let greeting = Tolgee.shared.translate("hello", bundle: bundle)
TolgeeText("hello", bundle: bundle)
```

> **NOTE:**
> A custom locale, whether set on the SDK or passed to the `translate` method, is matched against the localizations of the bundle the string is read from. Each bundle resolves on its own, so a package may carry a different set of localizations than the app, or name one differently (`pt` next to the app's `pt-BR`). The language fetched from the CDN is still chosen from the localizations of the app.

## Listening for updates

Tolgee provides a hook to allow the consumer of the SDK to be notified about when the translation cache has been updated.
Expand Down
47 changes: 38 additions & 9 deletions ios-sdk/get_started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Add to your `Package.swift`:

```swift
dependencies: [
.package(url: "https://github.com/tolgee/tolgee-mobile-swift-sdk", from: "1.0.0")
.package(url: "https://github.com/tolgee/tolgee-mobile-swift-sdk", from: "1.2.0")
]
```

Expand Down Expand Up @@ -60,46 +60,75 @@ You can customize the initialization with additional parameters:
// Initialize with specific language and namespaces
Tolgee.shared.initialize(
cdn: URL(string: "https://cdn.tolgee.io/your-project-id")!,
language: "es", // Force Spanish instead of auto-detection
locale: Locale(identifier: "pt_BR"), // Override the system locale
language: "pt-BR", // Override the language name on Tolgee CDN
namespaces: ["buttons", "errors", "onboarding"], // Organize translations
enableDebugLogs: true // Enable detailed logging for development
)
```

## Fetching remote translations
You have to explicitly call the `fetch` method to fetch translations from the CDN.
You have to explicitly call the `remoteFetch` method to fetch translations from the CDN.
```swift
await Tolgee.shared.remoteFetch()
```

## Generating typed keys

The SDK can generate a typed key for every key in your String Catalogs (`.xcstrings`), so a typo in a key or a wrong argument fails the build. The examples in this documentation use the generated keys.

To generate them, add the `TolgeeKeysPlugin` build tool plugin to your target in Xcode under `Build Phases` → `Run Build Tool Plug-ins`, or in your `Package.swift`:

```swift
.target(
name: "MyFeature",
dependencies: [.product(name: "Tolgee", package: "tolgee-mobile-swift-sdk")],
plugins: [.plugin(name: "TolgeeKeysPlugin", package: "tolgee-mobile-swift-sdk")]
)
```

Learn how the keys are named and how they work with tables and Swift packages in [Typed keys](./typed_keys.mdx).

## Basic Translation

Key names are converted to camel case and format specifiers become parameters. For example `app_title` becomes `.appTitle` and `welcome_user` with the text `Welcome, %@` becomes `.welcomeUser(_:)`.

```swift
// Simple string translation
let title = Tolgee.shared.translate("app_title")
let title = Tolgee.shared.translate(.appTitle)

// Translation with arguments
let welcomeMessage = Tolgee.shared.translate(.welcomeUser("John"))
let itemCount = Tolgee.shared.translate(.itemsCount(5))
let nameAndAge = Tolgee.shared.translate(.myNameIsAndImYearsOld("John", 30))
```

String keys work as well. Use them if you don't want to add the plugin or if the key is not known at build time:

```swift
let title = Tolgee.shared.translate("app_title")
let welcomeMessage = Tolgee.shared.translate("welcome_user", "John")
let itemCount = Tolgee.shared.translate("items_count", 5)
let nameAndAge = Tolgee.shared.translate("My name is %@ and I'm %lld years old", "John", 30)
```

> **NOTE:**
> Strings with multiple pluralized parameters are currently **not supported**,
> Strings with multiple pluralized parameters are currently **not supported** by the Over-the-Air updates and are always loaded from the app bundle,
> for example `Tolgee.shared.translate("I have %lld apples and %lld oranges", 2, 3)`

## Thread-safety

Tolgee SDK is designed to be used synchronously on the main actor (except the `fetch` method). Access to the SDK from other actors generally has to be awaited.
Tolgee SDK is designed to be used synchronously on the main actor (except the `remoteFetch` method). Access to the SDK from other actors generally has to be awaited.

```swift
Task.deattached {
Task.detached {
// notice that the call has to be awaited outside of the main actor
let str = await Tolgee.shared.translate("key")
let str = await Tolgee.shared.translate(.appTitle)
}
```

## Next steps

- __Typed keys__: Learn how the generated keys are named and how to use them — [Typed keys](./typed_keys.mdx)
- __SwiftUI compatibility__: Learn how Tolgee iOS SDK works with your SwiftUI code — [SwiftUI](./swiftui.mdx)
- __NSLocalizedString swizzling__: Learn how to achieve zero config integration by enabling method swizzling — [Swizzling](swizzling.mdx)
- __Advanced usage__: Tips and tricks for debugging and using the SDK with advanced codebases — [Advanced usage](./advanced.mdx)
Expand Down
38 changes: 27 additions & 11 deletions ios-sdk/swiftui.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@ image: /img/og-images/ios-sdk.png

Tolgee works great with SwiftUI, including previewing views in different localizations using SwiftUI previews.

You can use the `TolgeeText` component which will automatically use the injected locale on iOS 18.4+
The examples below use [typed keys](./typed_keys.mdx) generated from your String Catalogs. If you don't generate them, pass the key as a string instead, for example `TolgeeText("welcome_title")`.

You can use the `TolgeeText` component which will automatically use the injected locale
```swift
import SwiftUI
import Tolgee

struct ContentView: View {
var body: some View {
TolgeeText("welcome_title")
TolgeeText(.welcomeTitle)
}
}

Expand All @@ -31,18 +33,14 @@ struct ContentView: View {
}
```

or use a version of the `translate` method that accepts `locale` param on iOS 18.4 and newer. The older implementation will fall back to the system language.
or use a version of the `translate` method that accepts `locale` param.

```swift
struct ContentView: View {
@Environment(\.locale) var locale

var body: some View {
if #available(iOS 18.4, *) {
Text(Tolgee.shared.translate("welcome_title", locale: locale))
} else {
Text(Tolgee.shared.translate("welcome_title"))
}
Text(Tolgee.shared.translate(.welcomeTitle, locale: locale))
}
}

Expand All @@ -57,9 +55,27 @@ struct ContentView: View {
}
```

> **NOTE:**
> The `locale` parameter of the `translate` method is primarily intended for SwiftUI previews. When set to a non-current locale, translations from the CDN are ignored and only the localizations bundled with your app are used. A custom locale set on the SDK level via `initialize(...)` or `setCustomLocale(...)` takes precedence and the `locale` parameter is ignored. Learn more in [Language Overwrite](./advanced.mdx#language-overwrite).

## Parameters

Keys with parameters are generated as functions, so the arguments are checked by the compiler. Plurals work the same way, the right plural form is selected by the number you pass in.

```swift
TolgeeText(.welcomeUser("John"))
TolgeeText(.itemsCount(5))

// or with string keys
TolgeeText("welcome_user", "John")
TolgeeText("items_count", 5)
```

## Reactive updates

Tolgee offers a convenience utility that automatically triggers a redraw of a view when the translations cache has been updated.
`TolgeeText` automatically updates when the translations cache has been updated from the CDN.

For views that call the `translate` method directly, Tolgee offers a convenience utility that automatically triggers a redraw of a view when the translations cache has been updated.

```swift
struct ContentView: View {
Expand All @@ -70,8 +86,8 @@ struct ContentView: View {

var body: some View {
VStack {
TolgeeText("My name is %@ and I have %lld apples", "John", 3)
Text(Tolgee.shared.translate(.myNameIsAndIHaveApples("John", 3)))
}
}
}
```
```
3 changes: 3 additions & 0 deletions ios-sdk/swizzling.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ let welcomeMessage = String(format: NSLocalizedString("welcome_user", comment: "
> **NOTE:**
> Plural strings are currently not supported and will fall back to using the string bundled with the app.

> **TIP:**
> Swizzling is meant for existing code that already uses `NSLocalizedString`. For new code, consider using the SDK directly with [typed keys](./typed_keys.mdx), which support plurals and are checked at build time.

:::warning

Method swizzling is a powerful technique, but it can lead to unexpected behavior if not used carefully, especially if there is multiple SDKs swizzling the same APIs. Make sure to test your application thoroughly after enabling swizzling.
Expand Down
Loading
Loading