Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Apr 29, 2024

Set up Amplify DataStore

Amplify iOS v1 is deprecated as of June 1st, 2024. No new features or bug fixes will be added. Dependencies may become outdated and potentially introduce compatibility issues.

Please use the latest version (v2) of Amplify Library for Swift to get started. Refer to the upgrade guide for instructions on upgrading your application to the latest version.

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.

DataStore with Amplify

Amplify DataStore provides a programming model for leveraging shared and distributed data without writing additional code for offline and online scenarios, which makes working with distributed, cross-user data just as simple as working with local-only data.

Note: this allows you to start persisting data locally to your device with DataStore, even without an AWS account.

Goal

To setup and configure your application with Amplify DataStore and use it to persist data locally on a device.

Prerequisites

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

Install Amplify Libraries

  1. To install Amplify Libraries in your application, open your project in Xcode and select File > Add Packages....

  2. Enter the Amplify iOS GitHub repo URL (https://github.com/aws-amplify/amplify-swift) into the search bar and click Add Package.

Note: Up to Next Major Version should be selected from the Dependency Rule dropdown.

  1. Lastly, choose AWSDataStorePlugin and Amplify. Then click Add Package.

To install the Amplify DataStore to your application, add AmplifyPlugins/AWSDataStorePlugin. Your Podfile should look similar to:

target 'MyAmplifyApp' do
use_frameworks!
pod 'Amplify'
pod 'AmplifyPlugins/AWSDataStorePlugin'
end

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

pod install --repo-update

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

xed .

Setup local development environment

To use Amplify, you must first initialize it for use in your project. If you haven't already done so, run this command:

amplify init

The base structure for a DataStore app is created by adding a new GraphQL API to your app.

# For new APIs
amplify add api
# For existing APIs
amplify update api

The CLI will prompt you to configure your API. Select GraphQL as the API type and reply to the questions as shown below. Conflict detection is required when using DataStore to sync data with the cloud.

? Please select from one of the below mentioned services:
`GraphQL`
? Here is the GraphQL API that we will create. Select a setting to edit or continue:
`Name`
? Provide API name:
`BlogAppApi`
? Here is the GraphQL API that we will create. Select a setting to edit or continue:
`Authorization modes: API key (default, expiration time: 7 days from now)`
? Choose the default authorization type for the API
`API key`
? Enter a description for the API key:
`BlogAPIKey`
? After how many days from now the API key should expire (1-365):
`365`
? Configure additional auth types?
`No`
? Here is the GraphQL API that we will create. Select a setting to edit or continue:
`Conflict detection (required for DataStore): Disabled`
? Enable conflict detection?
`Yes`
? Select the default resolution strategy
`Auto Merge`
? Here is the GraphQL API that we will create. Select a setting to edit or continue:
`Continue`
? Choose a schema template
`Single object with fields (e.g., “Todo” with ID, name, description)`

Troubleshooting: Cloud sync will fail without the conflict detection configuration. To enable it for an existing project, run amplify update api and choose Enable DataStore for entire API.

The amplify add api command adds a new AmplifyConfig group to your Xcode project. It will contain the following files:

  • AmplifyConfig/
    • amplifyconfiguration.json
    • awsconfiguration.json
    • schema.graphql

Idiomatic persistence

DataStore relies on platform standard data structures to represent the data schema in an idiomatic way. The persistence language is composed by data types that satisfies the Model interface and operations defined by common verbs such as save, query and delete.

Data schema

The first step to create an app backed by a persistent datastore is to define a schema. DataStore uses GraphQL schema files as the definition of the application data model. The schema contains data types and relationships that represent the app's functionality.

Sample schema

For the next steps, let's start with a schema for a small blog application. Currently, it has only a single model. New types and constructs will be added to this base schema as more concepts are presented.

Open the schema.graphql file located by default at amplify/backend/{api_name}/ and define a model Post as follows.

type Post @model {
id: ID!
title: String!
status: PostStatus!
rating: Int
content: String
}
enum PostStatus {
ACTIVE
INACTIVE
}

Now you will to convert the platform-agnostic schema.graphql into platform-specific data structures. DataStore relies on code generation to guarantee schemas are correctly converted to platform code.

Like the initial setup, models can be generated either using the IDE integration or Amplify CLI directly.

Code generation: Platform integration

On iOS the amplify CLI offers an Xcode integration that automatically adds the Amplify-specific files to your project.

  1. Run the command:

    amplify codegen models
  2. The amplify codegen models command adds a new AmplifyModels group to your Xcode project. It will contain the following files:

  • AmplifyModels/
    • AmplifyModels.swift
    • Post.swift
    • Post+Schema.swift
    • PostStatus.swift
  1. Build the project (Cmd+b).

Code generation: Amplify CLI

Models can also be generated using the Amplify CLI directly.

In your terminal, make sure you are in your project/root folder and execute the codegen command:

amplify codegen models

You can find the generated files at amplify/generated/models/.

Initialize Amplify DataStore

To initialize the Amplify DataStore call Amplify.add(plugin:) method and add the AWSDataStorePlugin, then call Amplify.configure().

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

import Amplify
import AWSDataStorePlugin
import Amplify
import AmplifyPlugins

Add the following code

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

class AppDelegate: NSObject, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
do {
// AmplifyModels is generated in the previous step
let dataStorePlugin = AWSDataStorePlugin(modelRegistration: AmplifyModels())
try Amplify.add(plugin: dataStorePlugin)
try Amplify.configure()
print("Amplify configured with DataStore plugin")
} catch {
print("Failed to initialize Amplify with \(error)")
return false
}
return true
}
}

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

@main
struct MyAmplifyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}

Add to your AppDelegate's application:didFinishLaunchingWithOptions method

func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
do {
// AmplifyModels is generated in the previous step
let dataStorePlugin = AWSDataStorePlugin(modelRegistration: AmplifyModels())
try Amplify.add(plugin: dataStorePlugin)
try Amplify.configure()
print("Amplify configured with DataStore plugin")
} catch {
print("Failed to initialize Amplify with \(error)")
return false
}
return true
}

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

Amplify configured with DataStore plugin

Persistence operations

Now the application is ready to execute persistence operations. The data will be persisted to a local database, enabling offline-first use cases by default.

Even though a GraphQL API is already added to your project, the cloud synchronization will only be enabled when the API plugin is initialized and the backend provisioned. See the Next steps for more info.

Writing to the database

To write to the database, create an instance of the Post model and save it.

let post = Post(title: "Create an Amplify DataStore app",
status: .active)
Amplify.DataStore.save(post) { result in
switch result {
case .success:
print("Post saved successfully!")
case .failure(let error):
print("Error saving post \(error)")
}
}
let post = Post(title: "Create an Amplify DataStore app",
status: .active)
let saveSink = Amplify.DataStore.save(post).sink {
if case let .failure(error) = $0 {
print("Error saving post \(error)")
}
}
receiveValue: {
print("Post saved successfully! \($0)")
}

Reading from the database

To read from the database, the simplest approach is to query for all records of a given model type.

Amplify.DataStore.query(Post.self) { result in
switch result {
case .success(let posts):
print("Posts retrieved successfully: \(posts)")
case .failure(let error):
print("Error retrieving posts \(error)")
}
}
let querySink = Amplify.DataStore.query(Post.self).sink {
if case let .failure(error) = $0 {
print("Error retrieving posts \(error)")
}
}
receiveValue: { posts in
print("Posts retrieved successfully: \(posts)")
}

Next steps

Congratulations! You’ve created and retrieved data from the local database. Check out the following links to see other Amplify DataStore use cases and advanced concepts: