Page updated Nov 8, 2023

Connect to the cloud

Provision backend

Now that you have DataStore persisting data locally, in the next step you'll connect it to the cloud. With a couple of commands, you'll create an AWS AppSync API and configure DataStore to synchronize its data to it.

  1. Configure Amplify to manage cloud resources on your behalf. Open a terminal window and run amplify configure. This step will configure a new AWS user in your account for Amplify.

    1amplify configure

    This command will open up a web browser to the AWS Management Console and guide you through creating a new IAM user. For step-by-step directions to set this up, refer to the CLI installation guide.

  2. Initialize the Amplify backend. To do this, run the command and follow the step-by-step instructions:

    1amplify init
  3. Next, push your new backend to the cloud. To do this, run the command:

    1amplify push

Answer No to ? Do you want to generate code for your newly created GraphQL API. Answering Yes will generate an API.swift file which is only necessary when directly using the AWSAppSync SDK. When you're using Amplify API or Amplify DataStore, you'll use the amplify codegen models command to generate Swift models.

Note: Sit back and relax since this command will generate all the required cloud resources on your AWS account and it might take a while to complete.

Enable cloud syncing

In order to enable cloud syncing you need to configure your application to use the Amplify API category.

Open the TodoApp.swift file and add the following import statement:

1import AWSAPIPlugin

Then update the configureAmplify() function to call Amplify.add(plugin:) with a reference to an AWSAPIPlugin instance:

1func configureAmplify() {
2 let apiPlugin = AWSAPIPlugin(modelRegistration: AmplifyModels())
3 let dataStorePlugin = AWSDataStorePlugin(modelRegistration: AmplifyModels())
4 do {
5 try Amplify.add(plugin: apiPlugin)
6 try Amplify.add(plugin: dataStorePlugin)
7 try Amplify.configure()
8 print("Initialized Amplify");
9 } catch {
10 // simplified error handling for the tutorial
11 print("Could not initialize Amplify: \(error)")
12 }
13}

Now when you run your application the data will be synced to your cloud backend automatically! 🎉

Add a subscription

We will now demonstrate how to add a subscription to the application, so that you can receive any updates to the Todo model.

  1. Open ContentView.swift and add the following code to the body of the struct:
1func subscribeTodos() async {
2 do {
3 let mutationEvents = Amplify.DataStore.observe(Todo.self)
4 for try await mutationEvent in mutationEvents {
5 print("Subscription got this value: \(mutationEvent)")
6 do {
7 let todo = try mutationEvent.decodeModel(as: Todo.self)
8
9 switch mutationEvent.mutationType {
10 case "create":
11 print("Created: \(todo)")
12 case "update":
13 print("Updated: \(todo)")
14 case "delete":
15 print("Deleted: \(todo)")
16 default:
17 break
18 }
19 } catch {
20 print("Model could not be decoded: \(error)")
21 }
22 }
23 } catch {
24 print("Unable to observe mutation events")
25 }
26}
  1. Then remove any existing code you may have in the performOnAppear() function, and replace it with code calling the subscribeTodos() function. Your performOnAppear() function may look like this:
1func performOnAppear() async {
2 await subscribeTodos()
3}
  1. Build and run the application. In the console output if .info logging is enabled, you will see that you are making a websocket connection to receive updates any time there is a mutation to the Todo model.

Since this is the first time you are connecting to API, DataStore will sync any mutations that were previously made offline. If you have been following the guide, there should be one mutation that is synchronized to the backend that has an id of "Build iOS Application".

Query for mutations using the console

In this section you will make a mutation using the app sync console and have your app receive that mutation over the websocket subscription.

  1. Open a terminal window in your project's directory. Run the command:
1amplify console api

When prompted, select GraphQL. This will open the AWS AppSync console.

1? Please select from one of the below mentioned services: (Use arrow keys)
2 GraphQL
  1. Copy and paste the following query into the left pane:

    1query GetTodos {
    2 listTodos {
    3 items {
    4 id
    5 name
    6 description
    7 _deleted
    8 }
    9 }
    10}
  2. Press the play button to run the query. This will return all of the synchronized Todos in the right pane:

Create a mutation

  1. Synchronization will occur bi-directionally. Create an item in AWS AppSync by copying and pasting the following mutation:

    1mutation CreateTodo {
    2 createTodo(
    3 input: {
    4 name: "Tidy up the office",
    5 description: "Organize books, vacuum, take out the trash",
    6 priority: NORMAL
    7 }
    8 ) {
    9 id,
    10 name,
    11 description,
    12 priority,
    13 _version,
    14 _lastChangedAt,
    15 createdAt,
    16 updatedAt,
    17 }
    18}

  2. In the console output of your app, you should see:

1Subscription got this value: MutationEvent(id: "58220B03-6A42-4EB8-9C07-36019783B1BD", modelId: "0a0acfab-1014-4f25-959e-646a97b7013c", modelName: "Todo", json: "{\"id\":\"0a0acfab-1014-4f25-959e-646a97b7013c\",\"name\":\"Tidy up the office\",\"priority\":\"NORMAL\",\"description\":\"Organize books, vacuum, take out the trash\"}", mutationType: "create", createdAt: 2020-05-14 23:31:04 +0000, version: Optional(1), inProcess: false, graphQLFilterJSON: nil)