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 Storage

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.

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:

amplify add storage

Enter the following when prompted:

? Please select from one of the below mentioned services:
`Content (Images, audio, video, etc.)`
? 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?
`Yes`
? Do you want to use the default authentication and security configuration?
`Default configuration`
? How do you want users to be able to sign in?
`Username`
? Do you want to configure advanced settings?
`No, I am done.`
? Please provide a friendly name for your resource that will be used to label this category in the project:
`S3friendlyName`
? Please provide bucket name:
`storagebucketname`
? Who should have access:
`Auth and guest users`
? What kind of access do you want for Authenticated users?
`create/update, read, delete`
? What kind of access do you want for Guest users?
`create/update, read, delete`
? Do you want to add a Lambda Trigger for your S3 Bucket?
`No`

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

amplify 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:

target 'MyAmplifyApp' do
use_frameworks!
pod 'Amplify'
pod 'AmplifyPlugins/AWSS3StoragePlugin'
pod 'AmplifyPlugins/AWSCognitoAuthPlugin'
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 .

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:

import Amplify
import AWSS3StoragePlugin
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 {
try Amplify.add(plugin: AWSCognitoAuthPlugin())
try Amplify.add(plugin: AWSS3StoragePlugin())
try Amplify.configure()
print("Amplify configured with storage plugin")
} catch {
print("Failed to initialize Amplify with \(error)")
}
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 {
try Amplify.add(plugin: AWSCognitoAuthPlugin())
try Amplify.add(plugin: AWSS3StoragePlugin())
try Amplify.configure()
print("Amplify configured with storage plugin")
} catch {
print("Failed to initialize Amplify with \(error)")
}
return true
}

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

Amplify 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.

func uploadData() {
let dataString = "Example file contents"
let data = Data(dataString.utf8)
Amplify.Storage.uploadData(key: "ExampleKey", data: data,
progressListener: { progress in
print("Progress: \(progress)")
}, resultListener: { (event) in
switch event {
case .success(let data):
print("Completed: \(data)")
case .failure(let storageError):
print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
}
})
}
// In your type's instance variables
var resultSink: AnyCancellable?
var progressSink: AnyCancellable?
// ...
func uploadData() {
let dataString = "Example file contents"
let data = Data(dataString.utf8)
let storageOperation = Amplify.Storage.uploadData(key: "ExampleKey", data: data)
progressSink = storageOperation
.progressPublisher
.sink { progress in print("Progress: \(progress)") }
resultSink = storageOperation
.resultPublisher
.sink {
if case let .failure(storageError) = $0 {
print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
}
}
receiveValue: { data in
print("Completed: \(data)")
}
}

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: