tolgee/tolgee-mobile-swift-sdk
[Tolgee](https://tolgee.io/) is a powerful localization platform that simplifies the translation process for your applications.
What is Tolgee?
Tolgee is a powerful localization platform that simplifies the translation process for your applications. This SDK provides integration for iOS and macOS projects.
β¨ Features
- π Remote translation loading from Tolgee CDN with automatic updates
- π¦ Namespace-based organization for scalable translation management
- πΎ Intelligent caching with ETag support and background synchronization
- π Automatic fallback to bundle-based localizations when offline
- π― Smart language detection from device settings with manual override
- β‘ Modern async/await API for Swift concurrency
- π§ SwiftUI integration with reactive updates and
TolgeeTextcomponent - π± Multi-platform support for iOS, macOS, tvOS, and watchOS
- π Advanced debugging with comprehensive logging
Installation
[!NOTE] For managing static translations (used as fallback), check out tolgee-cli. It provides tools for updating and syncing your static translation files.
In each demo project you can find an example of
.tolgeercconfiguration file.
π Quick Start
Here's a quick example of initializing Tolgee in an iOS application:
import Tolgee
// Initialize with your Tolgee CDN URL
let cdnURL = URL(string: "https://cdn.tolgee.io/your-project-id")!
Tolgee.shared.initialize(cdn: cdnURL)
// Fetch latest translations asynchronously
await Tolgee.shared.remoteFetch()
// Use translations throughout your app
let greeting = Tolgee.shared.translate("hello_world")
let personalGreeting = Tolgee.shared.translate("hello_name", "Alice")π¦ Installation
Swift Package Manager
Add to your Package.swift:
dependencies: [
.package(url: "https://github.com/tolgee/tolgee-mobile-swift-sdk", from: "1.0.0")
]Or through Xcode:
- File β Add Package Dependencies...
- Enter:
https://github.com/tolgee/tolgee-mobile-swift-sdk - Choose version and add to your target
π― Basic Usage
Initialization
import Tolgee
// Set the CDN format to Apple in your Tolgee project
let cdnURL = URL(string: "https://cdn.tolgee.io/your-project-id")!
Tolgee.shared.initialize(cdn: cdnURL)Refer to our SwiftUI and UIKit examples for a complete setup.
Advanced Initialization
// Initialize with specific language and namespaces
Tolgee.shared.initialize(
cdn: URL(string: "https://cdn.tolgee.io/your-project-id")!,
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
)Fetch Remote Translations
You have to explicitly call the fetch method to fetch translations from the CDN.
await Tolgee.shared.remoteFetch()Basic Translation
// Simple string translation
let title = Tolgee.shared.translate("app_title")
// Translation with arguments
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, for example
Tolgee.shared.translate("I have %lld apples and %lld oranges", 2, 3)
π§ SwiftUI Integration
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
import SwiftUI
import Tolgee
struct ContentView: View {
var body: some View {
TolgeeText("welcome_title")
}
}
#Preview("English") {
ContentView()
.environment(\.locale, Locale(identifier: "en"))
}
#Preview("Czech") {
ContentView()
.environment(\.locale, Locale(identifier: "cs"))
}or use a version of the translate method that accepts locale param.
struct ContentView: View {
@Environment(\.locale) var locale
var body: some View {
Text(Tolgee.shared.translate("welcome_title", locale: locale))
}
}
#Preview("English") {
ContentView()
.environment(\.locale, Locale(identifier: "en"))
}
#Preview("Czech") {
ContentView()
.environment(\.locale, Locale(identifier: "cs"))
}[!NOTE] The
localeparameter intranslate(...)methods is primarily intended for SwiftUI previews. When set to a non-current locale, translations from the CDN will be ignored and only bundle localizations will be used. If a custom locale is set on the SDK level viainitialize(...)orsetCustomLocale(...), it will take precedence and the locale parameter will be ignored.
Reactive Updates
Tolgee provides a hook to allow the consumer of the SDK to be notified about when the translation cache has been updated.
Task {
for await _ in Tolgee.shared.onTranslationsUpdated() {
// update your UI
}
}When using SwiftUI, TolgeeText will automatically update. Tolgee additionally offers a convenience utility that automatically triggers a redraw of a view when the translations cache has been updated.
struct ContentView: View {
// This will automatically re-render the view when
// the localization cache is updated from a CDN.
@StateObject private var updater = TolgeeSwiftUIUpdater()
var body: some View {
VStack {
TolgeeText("My name is %@ and I have %lld apples", "John", 3)
}
}
}Swizzling of Apple's APIs
Tolgee optionally supports swizzling of Bundle.localizedString, which is being used by NSLocalizedString function. In order to enable swizzling, set enviromental variable TOLGEE_ENABLE_SWIZZLING=true in your scheme settings. Refer to our UIKit example to see it in action.
Following calls will then be backed by the Tolgee SDK:
Bundle.main.localizedString(forKey: "welcome_message")
NSLocalizedString("welcome_message", comment: "")[!NOTE] Plural strings are currently not supported and will fall back to using the string bundled with the app.
π Advanced Features
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
You can set a custom language when initializing Tolgee:
// Override both locale and language
Tolgee.shared.initialize(
cdn: cdnURL,
locale: Locale(identifier: "pt_BR"), // Override the system locale
language: "pt-BR" // Override the language name on Tolgee CDN
)
// Or just override the locale (language is extracted automatically)
Tolgee.shared.initialize(
cdn: cdnURL,
locale: Locale(identifier: "pt_BR")
)Changing Language at Runtime
Use setCustomLocale(_:language:) to change the language dynamically:
// Set custom locale (language is extracted automatically)
try Tolgee.shared.setCustomLocale(Locale(identifier: "fr"))
// Or specify a custom language for the CDN if it differs from the locale
try Tolgee.shared.setCustomLocale(
Locale(identifier: "pt_BR"),
language: "pt-BR" // CDN language code
)
// Fetch translations for the new language
await Tolgee.shared.remoteFetch()Resetting to System Language
To return to the device's system language:
try Tolgee.shared.setCustomLocale(.current)
await Tolgee.shared.remoteFetch()Pre-fetching all available languages from the CDN
You can pre-fetch all languages supported by your app:
await withTaskGroup(of: Void.self) { group in
for language in Bundle.main.localizations {
group.addTask {
await Tolgee.shared.remoteFetch(language: language)
}
}
}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.
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.
// Initialize with multiple namespaces for better organization
Tolgee.shared.initialize(
cdn: cdnURL,
namespaces: ["common", "auth", "profile", "settings"]
)
// Use translations from specific namespaces
let commonGreeting = Tolgee.shared.translate("hello", table: "common")
// or for SwiftUI
TolgeeText("hello", table: "common")Custom Bundles
You may have your strings resources stored in a dedicated XCFramework or a Swift Package.
let bundle: Bundle = ... // access the bundle
// Use the SDK directly
let commonGreeting = Tolgee.shared.translate("hello", bundle: bundle)
// or for SwiftUI
TolgeeText("hello", bundle: bundle)Log Forwarding
Tolgee allows forwarding of logs that are printed to the console by default. You can use this feature to forward errors and other logs into your analytics.
for await logMessage in Tolgee.shared.onLogMessage() {
// Here you can forward logs from Tolgee SDK to your analytics SDK.
}π± Platform Support
| Platform | Minimum Version | |----------|----------------| | iOS | 16.0+ | | macOS | 13.0+ | | tvOS | 16.0+ | | watchOS | 6.0+ |
βοΈ Requirements
- Swift: 6.0+
- Xcode: 16.0+
π§΅ 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.
Task.deattached {
// notice that the call has to be awaited outside of the main actor
let str = await Tolgee.shared.translate("key")
}π€ Why Choose Tolgee?
Tolgee saves a lot of time you would spend on localization tasks otherwise. It enables you to provide perfectly translated software.
All-in-one localization solution for your iOS application π
Translation management platform π
Open-source π₯
π Examples & Demos
Check out our example projects:
π Need Help?
- π Documentation
- π¬ Community Slack
- π Report Issues
- π‘ Feature Requests
ποΈ Contributing
Contributions are welcome!
π License
This project is licensed under the MIT License - see the LICENSE file for details.
<p align="center"> <a href="https://tolgee.io"> <img src="https://user-images.githubusercontent.com/18496315/188628892-33fcc282-44f1-4926-8be4-d0db5a2420ca.png" alt="Tolgee" /> </a> </p>
<p align="center"> Made with β€οΈ by the <a href="https://github.com/tolgee">Tolgee team</a> </p>
Package Metadata
Repository: tolgee/tolgee-mobile-swift-sdk
Default branch: main
README: README.md