Page updated Jan 16, 2024

Set up Amplify Storage

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 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 iOS application targeting at least iOS 11.0 with Amplify libraries integrated

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

  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 AWSS3StoragePlugin, AWSCognitoAuthPlugin, and Amplify. Then click Add Package.

To install the Amplify Storage and Authentication to your application, add both AmplifyPlugins/AWSS3StoragePlugin and AmplifyPlugins/AWSCognitoAuthPlugin to your Podfile. Your Podfile should look similar to:

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

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 Storage

To initialize the Amplify Storage 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 AWSS3StoragePlugin
1import Amplify
2import AmplifyPlugins

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: AWSS3StoragePlugin())
10 try Amplify.configure()
11 print("Amplify configured with storage plugin")
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: AWSS3StoragePlugin())
9 try Amplify.configure()
10 print("Amplify configured with storage plugin")
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 storage plugin

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() {
2 let dataString = "Example file contents"
3 let data = Data(dataString.utf8)
4 Amplify.Storage.uploadData(key: "ExampleKey", data: data,
5 progressListener: { progress in
6 print("Progress: \(progress)")
7 }, resultListener: { (event) in
8 switch event {
9 case .success(let data):
10 print("Completed: \(data)")
11 case .failure(let storageError):
12 print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
13 }
14 })
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 storageOperation = Amplify.Storage.uploadData(key: "ExampleKey", data: data)
11 progressSink = storageOperation
12 .progressPublisher
13 .sink { progress in print("Progress: \(progress)") }
14
15 resultSink = storageOperation
16 .resultPublisher
17 .sink {
18 if case let .failure(storageError) = $0 {
19 print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
20 }
21 }
22 receiveValue: { data in
23 print("Completed: \(data)")
24 }
25}

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: