Page updated Jan 16, 2024

Set up Predictions

Amplify iOS v1 is now in Maintenance Mode until May 31st, 2024. This means that we will continue to include updates to ensure compatibility with backend services and security. No new features will be introduced in v1.

Please use the latest version (v2) of Amplify Library for Swift to get started.

If you are currently using v1, follow these instructions to upgrade to v2.

Amplify libraries should be used for all new cloud connected applications. If you are currently using the AWS Mobile SDK for iOS, you can access the documentation here.

The Predictions category enables you to integrate machine learning into your application without any prior machine learning experience. It supports translating text from one language to another, converting text to speech, text recognition from an image, entities recognition, labeling real world objects, interpretation of text, and uploading images for automatic training. This functionality is powered by AWS services including: Amazon Translate, Amazon Polly, Amazon Transcribe, Amazon Rekognition, Amazon Textract, and Amazon Comprehend.

On iOS, we leverage Apple’s Core ML Vision Framework and Natural Language Framework to improve accuracy as well as support cases where your device is unable to reach AWS Services. For more information, see each individual use case.

Goal

To setup and configure your application with Amplify Predictions and go through a simple example of translating text.

Prerequisites

  • An iOS application targeting at least iOS 13.0 with Amplify libraries integrated

Provision Backend Services

To use the predictions category you will need to setup the auth backend resources. To provision auth resources in the backend, go to your project directory and execute the command:

1amplify add predictions

Enter the following when prompted:

1? Please select from one of the categories below
2 `Convert`
3? You need to add auth (Amazon Cognito) to your project in order to add storage for user files. Do you want to add auth now? (Y/n)
4 `Y`
5? Do you want to use the default authentication and security configuration?
6 `Default configuration`
7? How do you want users to be able to sign in?
8 `Email`
9? Do you want to configure advanced settings?
10 `No, I am done.`
11? What would you like to convert?
12 `Translate text into a different language`
13? Provide a friendly name for your resource
14 `transTextSample`
15? What is the source language?
16 `English`
17? What is the target language?
18 `Italian`
19? Who should have access?
20 ` Auth and Guest users`

Note that the languages selected during this stage will be the default language your app will translate to/from. These source and target languages can be overridden when you write the code in your application.

To push your change to the cloud, execute the command:

1amplify push

Upon completion, amplifyconfiguration.json will be updated to reference the newly provisioned backend resources.

Install Amplify Libraries

To install the libraries required to translating text, add both AWSPredictionsPlugin and CoreMLPredictionsPlugin to your Podfile. Your Podfile should look similar to:

1target 'MyAmplifyApp' do
2 use_frameworks!
3 pod 'Amplify'
4 pod 'AmplifyPlugins/AWSCognitoAuthPlugin'
5 pod 'AWSPredictionsPlugin'
6 pod 'CoreMLPredictionsPlugin'
7end

To install, download and resolve these pods, execute the command:

1pod install --repo-update

Now you can open your project by opening the .xcworkspace file using the following command:

1xed .

Initialize Amplify Predictions

To initialize the Amplify Predictions and Authentication categories, you are required to use the Amplify.add() method for each category you want. When you are done calling add() on each category, you finish configuring Amplify by calling Amplify.configure().

Add the following imports to the top of your AppDelegate.swift file:

1import Amplify
2import AmplifyPlugins
3import AWSPredictionsPlugin

Add the following code

Create a custom AppDelegate, and add to your application:didFinishLaunchingWithOptions method

1class AppDelegate: NSObject, UIApplicationDelegate {
2 func application(
3 _ application: UIApplication,
4 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
5 ) -> Bool {
6
7 do {
8 try Amplify.add(plugin: AWSCognitoAuthPlugin())
9 try Amplify.add(plugin: AWSPredictionsPlugin())
10 try Amplify.configure()
11 print("Amplify configured with Auth and Predictions plugins")
12 } catch {
13 print("Failed to initialize Amplify with \(error)")
14 }
15
16 return true
17 }
18}

Then in the App scene, use UIApplicationDelegateAdaptor property wrapper to use your custom AppDelegate

1@main
2struct MyAmplifyApp: App {
3 @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
4
5 var body: some Scene {
6 WindowGroup {
7 ContentView()
8 }
9 }
10}

Add to your AppDelegate's application:didFinishLaunchingWithOptions method

1func application(
2 _ application: UIApplication,
3 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
4) -> Bool {
5
6 do {
7 try Amplify.add(plugin: AWSCognitoAuthPlugin())
8 try Amplify.add(plugin: AWSPredictionsPlugin())
9 try Amplify.configure()
10 print("Amplify configured with Auth and Predictions plugins")
11 } catch {
12 print("Failed to initialize Amplify with \(error)")
13 }
14
15 return true
16}

Upon building and running this application you should see the following in your console window:

1Amplify configured with Auth and Predictions plugins

Translating text

To translate text from one language to another, specify the text you want translated, a source language, and a target language. The source and target language parameters will override any choice you made while adding this resource using the Amplify CLI.

1func translateText() {
2 Amplify.Predictions.convert(textToTranslate: "I like to eat spaghetti",
3 language: .english,
4 targetLanguage: .spanish,
5 listener: { (event) in
6 switch event {
7 case .success(let result):
8 print(result.text)
9 case .failure(let error):
10 print("Error: \(error)")
11 }
12 })
13}
1func translateText() -> AnyCancellable {
2 Amplify.Predictions.convert(
3 textToTranslate: "I like to eat spaghetti",
4 language: .english,
5 targetLanguage: .spanish
6 )
7 .resultPublisher
8 .sink {
9 if case let .failure(error) = $0 {
10 print("Error: \(error)")
11 }
12 }
13 receiveValue: { result in
14 print(result.text)
15 }
16}

As a result of executing this code, you will see the following printed to your console:

1Me gusta comer espaguetis

Next steps

Congratulations! You've translated text from one language to another. Check out the following links to explore other Amplify Predictions use cases: