Page updated Mar 6, 2024

Set up Amplify Storage

The Amplify Storage category provides an interface for managing user content for your app in public, protected, or private storage buckets. The Storage category comes with default built-in support for Amazon Simple Storage Service (S3). The Amplify CLI helps you to create and configure the storage buckets for your app. The Amplify AWS S3 Storage plugin leverages Amazon S3.

Goal

To setup and configure your application with Amplify Storage and go through a simple upload file example

Prerequisites

An application with Amplify libraries integrated and a minimum target of any of the following:

  • iOS 13.0, using Xcode 14.1 or later.
  • macOS 10.15, using Xcode 14.1 or later.
  • tvOS 13.0, using Xcode 14.3 or later.
  • watchOS 9.0, using Xcode 14.3 or later.
  • visionOS 1.0, using Xcode 15 beta 2 or later. (Preview support - see below for more details.)

For a full example, please follow the project setup walkthrough.

visionOS support is currently in preview and can be used by targeting the visionos-preview branch. As new Xcode 15 beta versions are released, the branch will be updated with any necessary fixes on a best effort basis.

For more information on how to use the visionos-preview branch, see Platform Support.

Provision backend storage

To start provisioning storage resources in the backend, go to your project directory and execute the command:

1amplify add storage

Enter the following when prompted:

1? Please select from one of the below mentioned services:
2 `Content (Images, audio, video, etc.)`
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?
4 `Yes`
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 `Username`
9? Do you want to configure advanced settings?
10 `No, I am done.`
11? Please provide a friendly name for your resource that will be used to label this category in the project:
12 `S3friendlyName`
13? Please provide bucket name:
14 `storagebucketname`
15? Who should have access:
16 `Auth and guest users`
17? What kind of access do you want for Authenticated users?
18 `create/update, read, delete`
19? What kind of access do you want for Guest users?
20 `create/update, read, delete`
21? Do you want to add a Lambda Trigger for your S3 Bucket?
22 `No`

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

1amplify push

Upon completion, amplifyconfiguration.json will be updated to reference a newly provisioned S3 bucket. Note that this file should already be a part of your project if you followed the Project setup walkthrough.

Install Amplify Libraries

Swift Package Manager

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

  2. Enter the Amplify Library for Swift 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 AWSS3StoragePlugin, AWSCognitoAuthPlugin, and Amplify. Then click Add Package.

Initialize Amplify Storage

To use the Amplify Storage and Authentication categories in your app, you need to create and configure their corresponding plugins by calling the Amplify.add(plugin:) and Amplify.configure() methods.

Add the following imports to the top of your App scene and configure Amplify in the init:

1import Amplify
2import AWSCognitoAuthPlugin
3import AWSS3StoragePlugin
4
5@main
6struct MyAmplifyApp: App {
7 var body: some Scene {
8 WindowGroup {
9 ContentView()
10 }
11 }
12
13 init() {
14 do {
15 try Amplify.add(plugin: AWSCognitoAuthPlugin())
16 try Amplify.add(plugin: AWSS3StoragePlugin())
17 try Amplify.configure()
18 print("Amplify configured with Auth and Storage plugins")
19 } catch {
20 print("Failed to initialize Amplify with \(error)")
21 }
22 }
23}

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

1import Amplify
2import AWSCognitoAuthPlugin
3import AWSS3StoragePlugin

Add the following code to the application:didFinishLaunchingWithOptions method:

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

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

1Amplify configured with Auth and Storage plugins

Uploading data to your bucket

To upload to S3 from a data object, specify the key and the data object to be uploaded.

1func uploadData() async throws {
2 let dataString = "Example file contents"
3 let data = Data(dataString.utf8)
4 let uploadTask = Amplify.Storage.uploadData(
5 key: "ExampleKey",
6 data: data
7 )
8 Task {
9 for await progress in await uploadTask.progress {
10 print("Progress: \(progress)")
11 }
12 }
13 let value = try await uploadTask.value
14 print("Completed: \(value)")
15}
1// In your type's instance variables
2var resultSink: AnyCancellable?
3var progressSink: AnyCancellable?
4
5// ...
6
7func uploadData() {
8 let dataString = "Example file contents"
9 let data = Data(dataString.utf8)
10 let uploadTask = Amplify.Storage.uploadData(
11 key: "ExampleKey",
12 data: data
13 )
14 progressSink = uploadTask
15 .inProcessPublisher
16 .sink { progress in
17 print("Progress: \(progress)")
18 }
19
20 resultSink = uploadTask
21 .resultPublisher
22 .sink {
23 if case let .failure(storageError) = $0 {
24 print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
25 }
26 }
27 receiveValue: { data in
28 print("Completed: \(data)")
29 }
30}

Upon successfully executing this code, you should see a new folder in your bucket, called public. It should contain a file called ExampleKey, whose contents is Example file contents.

Next Steps

Congratulations! You've uploaded a file to an s3 bucket. Check out the following links to see other Amplify Storage use cases: