TranslationSession
A class that performs translations between a pair of languages.
Declaration
class TranslationSessionOverview
This class provides a flexible way for you to translate one or more lines of text at a time. There are two ways in which you can initialize a TranslationSession. One way you can obtain an instance of this class is by adding a .translationTask() to a SwiftUI view within your app. You can either add a translationTask(_:action:) or a translationTask(source:target:action:) function to the SwiftUI view containing the content you want to translate, like a Text view. After adding the task, the function passes you an instance of a translation session in its action closure. With this instance, you can use one or more of the translate functions to translate a single string or multiple strings of text.
Another way for contexts where there’s no UI, you can directly initialize the TranslationSession using init(installedSource:target:) to translate between languages. This initializer requires that you specify which source language you use and throws an error if the languages aren’t already installed on the person’s device.
The following example demonstrates how to translate a single string of text within a SwiftUI view:
struct TranslationExample: View {
var sourceText: String
var sourceLanguage: Locale.Language?
var targetLanguage: Locale.Language?
@State private var targetText: String?
var body: some View {
Text(targetText ?? sourceText)
.translationTask(
source: sourceLanguage,
target: targetLanguage
) { session in
do {
let response = try await session.translate(sourceText)
targetText = response.targetText
} catch {
// Handle error.
}
}
}
}Topics
Initalizing a translation session
Preparing for translation
Getting the language configuration
Translating the text
translate(_:)translate(_:)translate(batch:)translations(from:)TranslationSession.RequestTranslationSession.ResponseTranslationSession.BatchResponse