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.
-
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.amplify configureThis 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.
-
Initialize the Amplify backend. To do this, run the command and follow the step-by-step instructions:
amplify init -
Next, push your new backend to the cloud. To do this, run the command:
amplify 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.
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:
import AWSAPIPlugin
Then update the configureAmplify()
function to call Amplify.add(plugin:)
with a reference to an AWSAPIPlugin
instance:
func configureAmplify() { let apiPlugin = AWSAPIPlugin(modelRegistration: AmplifyModels()) let dataStorePlugin = AWSDataStorePlugin(modelRegistration: AmplifyModels()) do { try Amplify.add(plugin: apiPlugin) try Amplify.add(plugin: dataStorePlugin) try Amplify.configure() print("Initialized Amplify"); } catch { // simplified error handling for the tutorial print("Could not initialize Amplify: \(error)") }}
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.
- Open
ContentView.swift
and add the following code to the body of the struct:
func subscribeTodos() async { do { let mutationEvents = Amplify.DataStore.observe(Todo.self) for try await mutationEvent in mutationEvents { print("Subscription got this value: \(mutationEvent)") do { let todo = try mutationEvent.decodeModel(as: Todo.self) switch mutationEvent.mutationType { case "create": print("Created: \(todo)") case "update": print("Updated: \(todo)") case "delete": print("Deleted: \(todo)") default: break } } catch { print("Model could not be decoded: \(error)") } } } catch { print("Unable to observe mutation events") }}
- Then remove any existing code you may have in the
performOnAppear()
function, and replace it with code calling the subscribeTodos() function. YourperformOnAppear()
function may look like this:
func performOnAppear() async { await subscribeTodos()}
- 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.
- Open a terminal window in your project's directory. Run the command:
amplify console api
When prompted, select GraphQL. This will open the AWS AppSync console.
? Please select from one of the below mentioned services: (Use arrow keys) GraphQL
-
Copy and paste the following query into the left pane:
query GetTodos {listTodos {items {idnamedescription_deleted}}} -
Press the play button to run the query. This will return all of the synchronized Todos in the right pane:
Create a mutation
-
Synchronization will occur bi-directionally. Create an item in AWS AppSync by copying and pasting the following mutation:
mutation CreateTodo {createTodo(input: {name: "Tidy up the office",description: "Organize books, vacuum, take out the trash",priority: NORMAL}) {id,name,description,priority,_version,_lastChangedAt,createdAt,updatedAt,}} -
In the console output of your app, you should see:
Subscription 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)