HomeiOS DevelopmentUtilizing Translation API in Swift and SwiftUI

Utilizing Translation API in Swift and SwiftUI


iOS already features a system-wide translation characteristic that permits customers to simply translate textual content into numerous languages. With the discharge of iOS 17.4 (and iOS 18), now you can leverage the brand new Translation API to combine this highly effective translation functionality into your apps.

Apple supplies two choices for builders to make the most of the Translation API. The quickest and easiest technique is to make use of the .translationPresentation modifier, which shows a translation overlay in your app. For a extra versatile resolution, you may immediately name the Translation API to construct a customized translation characteristic.

On this tutorial, we’ll discover each approaches and information you thru their implementation utilizing a SwiftUI demo app. Please word that you will want Xcode 16 to observe alongside.

Utilizing the translationPresentation Modifier

Let’s begin with the simple method: the .translationPresentation modifier. In Safari, customers can spotlight any textual content to entry the interpretation choice, which then shows a translation overlay with the translated textual content.

If you wish to carry this translation overlay to your app, all you want is to import the Translation bundle and use the .translationPresentation modifier. Check out the next pattern code:

import SwiftUI
import Translation

struct ContentView: View {
    
    @State personal var showTranslation = false
    @State personal var sampleText = article
    
    var physique: some View {
        VStack {
            Textual content(sampleText)
                .font(.system(.physique, design: .rounded))
                
            Button("Translate") {
                showTranslation.toggle()
            }
            .controlSize(.extraLarge)
            .buttonStyle(.borderedProminent)          
        }
        .padding()
        .translationPresentation(isPresented: $showTranslation, textual content: article)
    }
}

The app shows some pattern textual content in English with a Translate button positioned under it.

Now, if you faucet the “Translate” button, a translation overlay seems, displaying the translated textual content in your required language. Aside from iOS, the Translation API additionally works on each iPadOS and macOS. At present, this translation characteristic can’t be examined in Xcode Preview; you should deploy the app onto an actual system for testing.

The .translationPresentation modifier means that you can specify an optionally available motion to be carried out when customers faucet the “Change with Translation” button. As an illustration, if you wish to exchange the unique textual content with the translated textual content when the button is tapped, you may outline this motion like this:

.translationPresentation(isPresented: $showTranslation, textual content: article) { translatedText in
    
    sampleText = translatedText
    
}

When you specify the motion within the modifier, you will notice the “Change with Translation” choice within the translation overlay.

Working with the Translation API

For better management over translations, you need to use the Translation API immediately as an alternative of counting on the interpretation overlay. As an illustration, in case your app shows a listing of article excerpts and also you wish to supply translation assist, the interpretation overlay won’t be very best as a result of customers must choose every excerpt individually for translation.

A extra environment friendly resolution is to carry out a batch translation of all of the article excerpts when customers faucet the “Translate” button. Let’s create a easy demo to see how you can work with the Translation API and deal with batch translations.

Beneath is the pattern code for creating the UI above:

struct BatchTranslationDemo: View {
    
    @State personal var articles = sampleArticles
    
    var physique: some View {
        NavigationStack {
            Record(articles) { article in
                
                VStack {
                    Textual content(article.textual content)
                    
                    if article.translatedText != "" {
                        Textual content(article.translatedText)
                            .body(maxWidth: .infinity, alignment: .main)
                            .padding()
                            .background(Colour(.systemGray4))
                    }
                }
                
            }
            .listStyle(.plain)

            .toolbar {
                Button {
                    
                } label: {
                    Label("Translate", systemImage: "translate")
                        .labelStyle(.iconOnly)
                }

            }
        }
        
    }
}

To carry out a batch translation, you first have to outline a translation configuration that specifies each supply and goal languages. Within the code, you may declare a state variable to carry the configuration like under:

@State personal var configuration: TranslationSession.Configuration?

After which, within the closure of the toolbar’s Button, we are able to instantiate the configuration:

Button {
    
    if configuration == nil {
        configuration = TranslationSession.Configuration(supply: .init(identifier: "en-US"), goal: .init(identifier: "zh-Hant-TW"))
        return
    }
    
    configuration?.invalidate()
    
} label: {
    Label("Translate", systemImage: "translate")
        .labelStyle(.iconOnly)
}

We specify English because the supply language and Conventional Chinese language because the goal language. If you don’t specify the languages, the Translation API will mechanically create a default configuration, with iOS figuring out the supply and goal languages for you.

To carry out translation, you connect the .translationTask modifier to the checklist view:

Record(articles) { article in
	.
	.
	.
}
.translationTask(configuration) { session in
    
    let requests = articles.map { TranslationSession.Request(sourceText: $0.textual content, clientIdentifier: $0.id.uuidString) }
    
    if let responses = strive? await session.translations(from: requests) {
        
        responses.forEach { response in
            updateTranslation(response: response)
        }
    }
}

This modifier initiates a translation activity utilizing the required configuration. Each time the configuration modifications and isn’t nil, the interpretation activity is executed. Throughout the closure, we put together a set of translation requests and use the session’s translations(from:) technique to carry out a batch translation.

If the interpretation activity succeeds, it returns an array of translation responses containing the translated textual content. We then go this translated textual content to the updateTranslation technique to show it on display.

func updateTranslation(response: TranslationSession.Response) {
    
    guard let index = articles.firstIndex(the place: { $0.id.uuidString == response.clientIdentifier }) else {
        return
    }
    
    articles[index].translatedText = response.targetText
    
}

Let’s deploy the app to an actual system for testing. I examined the app on my iPad Air. Whenever you faucet the “Translate” button, the app ought to show further article excerpts in Conventional Chinese language.

Abstract

With the brand new Translation API launched in iOS 17.4 (and iOS 18), builders can now simply combine highly effective translation options into their apps. This tutorial covers two main strategies for using the API: the straightforward method utilizing the .translationPresentation modifier for displaying a translation overlay, and a extra versatile method utilizing the Translation API immediately for customized translation options.

We display each approaches on this tutorial. As illustrated within the demo, you may simply add translation capabilities with only a few strains of code. Given the simplicity and energy of this API, there’s no motive to not embrace translation performance in your apps.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments