Wesley de Groot's Blog
Translation framework in Swift

Back

Exploring the Translation Framework in Swift

With the release of iOS 17.4, Apple introduced the Translation framework, a powerful tool that allows developers to integrate text translation capabilities directly into their Swift applications. This framework leverages CoreML models to perform on-device translations, ensuring fast and secure translations without the need for an internet connection.

Key Features

  1. On-Device Translation: Unlike third-party services that require an internet connection, the Translation framework performs translations on-device, enhancing speed and security.
  2. Built-in UI: The framework offers a built-in user interface for translations, making it easy to integrate without extensive customization.
  3. Customizable Experience: For developers who need more control, the framework provides APIs to customize the translation process.

Getting Started

To demonstrate how to use the Translation framework, let's build a simple SwiftUI app that translates text input by the user.

Using the Built-in User Interface

We can achive this by using the .translationPresentation(isPresented:text:) view modifier provided by the translation framework.
This modifier presents a built-in translation UI that allows users to input text and view the translated output. it also provides a callback to handle the translated text if needed.

There are two ways to use the built-in UI:

Only show the translation

.translationPresentation(isPresented: $showTranslation, text: text)

Handle the translated text

.translationPresentation(isPresented: $showTranslation, text: text) { translatedText in
    text = translatedText
}

Example code

import SwiftUI
import Translation

struct ContentView: View {
    /// Text to be translated
    @State
    var text = "Swift programming is fun! You should try it yourself, it even has a translation framework now!"

    /// Should we show the translation UI
    @State
    var showTranslation = false

    var body: some View {
        NavigationStack {
            VStack {
                // Display the text to be translated
                Text(text)
                    .font(.title3)
                    .multilineTextAlignment(.center)
            }

            // Show translation UI
            .translationPresentation(
                isPresented: $showTranslation, 
                text: text
            ) { translatedText in
                // Optional: Handle the translated text
                text = translatedText
            }

            // Add a button to show the translation UI
            .toolbar {
                Button {
                    // Toggle the translation UI
                    showTranslation.toggle()
                } label: {
                    Image(systemName: "translate")
                }
            }
        }
    }
}

Using your own User Interface

The Translation framework also provides APIs to create a custom translation experience. By using the view modifier, you can initiate translation tasks and handle the translated text within your app's UI.

Inline translation using the .translationTask(_:action:) view modifier (user initiated translation)

The .translationTask(_:action:) view modifier allows you to create a custom translation experience where users can initiate translation tasks by interacting with your app's UI.

struct ContentView: View {
    /// Source text for translation
    @State
    private var sourceText = "Swift programming is fun! You should try it yourself, it even has a translation framework now!"

    /// Source text for translation
    var sourceLanguage: Locale.Language?

    /// Target language for translation
    var targetLanguage: Locale.Language?

    /// Translated text
    @State
    private var targetText: String?

    /// Translation session configuration
    @State
    private var configuration: TranslationSession.Configuration?

    var body: some View {
        VStack {
            Text(targetText ?? sourceText)
            Button("Translate") {
                guard configuration == nil else {
                    configuration?.invalidate()
                    return
                }

                // Create a new translation session configuration
                configuration = TranslationSession.Configuration(
                    source: sourceLanguage,
                    target: targetLanguage
                )
            }
            // Start translation task
            .translationTask(configuration) { session in
                Task { @MainActor in
                    do {
                        // Perform translation
                        let response = try await session.translate(sourceText)

                        // Update target text
                        targetText = response.targetText
                    } catch {
                        // code to handle error
                    }
                }
            }
        }
    }
}

Inline translation using the .translationTask(source:target:action:) view modifier (automatic translation)

.translationTask(source:target:action:) view modifier allows you to create a custom translation experience where users do not need to initiate translation tasks.

import SwiftUI
import Translation

struct ContentView: View {
    /// Source text for translation
    @State
    private var sourceText = "Swift programming is fun! You should try it yourself, it even has a translation framework now!"

    /// Source language for translation
    var sourceLanguage: Locale.Language?

    /// Target language for translation
    var targetLanguage: Locale.Language?

    /// Translated text
    @State
    private var targetText: String?

    var body: some View {
        Text(targetText ?? sourceText)
            // Start translation task
            .translationTask(
                source: sourceLanguage,
                target: targetLanguage
            ) { session in
                Task { @MainActor in
                    do {
                        // Perform translation
                        let response = try await session.translate(sourceText)

                        // Update target text
                        targetText = response.targetText
                    } catch {
                        // code to handle error
                    }
                }
            }
    }
}

Conclusion

The Translation framework in Swift opens up new possibilities for creating multilingual applications with ease. By leveraging on-device translations, developers can provide a seamless and secure user experience. Whether you use the built-in UI or customize the translation process, this framework is a valuable addition to your development toolkit.

Read more

Share


Share Mastodon Twitter LinkedIn Facebook
x-twitter mastodon github linkedin discord threads instagram whatsapp bluesky square-rss sitemap