Working with files / attachments
The Storage and GraphQL API categories can be used together to associate a file, such as an image or video, with a particular record. For example, you might create a User
model with a profile picture, or a Post
model with an associated image. With Amplify's GraphQL API and Storage categories, you can reference the file within the model itself to create an association.
To get started, go to your project directory and run the command:
1amplify add api
Choose the following when prompted:
1? Select from one of the below mentioned services: `GraphQL`2? Choose the default authorization type for the API `Amazon Cognito User Pool`3 Do you want to use the default authentication and security configuration? `Default configuration`4 How do you want users to be able to sign in? `Username`5 Do you want to configure advanced settings? `No, I am done.`6? Here is the GraphQL API that we will create. Select a setting to edit or continue `Continue`7? Choose a schema template: `Blank Schema`
When prompted, use the following schema, which can also be found under amplify/backend/api/[name of project]/schema.graphql
:
1type Song @model @auth(rules: [{ allow: public }]) {2 id: ID!3 name: String!4 coverArtKey: String # Set as optional to allow adding file after initial create5}
Add Storage with the command:
1amplify add storage
Choose the following when prompted:
1? Select from one of the below mentioned services: `Content (Images, audio, video, etc.)`2✔ Who should have access: `Auth users only`3✔ What kind of access do you want for Authenticated users? `create/update, read, delete`4✔ Do you want to add a Lambda Trigger for your S3 Bucket? (y/N) · `no`
Run amplify push
to deploy the changes.
Once the backend has been provisioned, run amplify codegen models
to generate the Swift model types for the app.
Next, add the Amplify(https://github.com/aws-amplify/amplify-swift.git
) package to your Xcode project and select the following modules to import when prompted:
- AWSAPIPlugin
- AWSCognitoAuthPlugin
- AWSS3StoragePlugin
- Amplify
Add the Authenticator from Amplify UI Authenticator for SwiftUI (https://github.com/aws-amplify/amplify-ui-swift-authenticator.git
)
Configuring authorization
Your application needs authorization credentials for reading and writing to both Storage and the GraphQL API, except in the case where all data and files are intended to be publicly accessible.
The Storage and API categories govern data access based on their own authorization patterns, meaning that it's necessary to configure appropriate auth roles for each individual category. Although both categories share the same access credentials set up through the Auth category, they work independently from one another. For instance, adding an @auth
directive to the API schema does not guard against file access in the Storage category. Likewise, adding authorization rules to the Storage category does not guard against data access in the API category.
When you run amplify add storage
, the CLI will configure appropriate IAM policies on the bucket using a Cognito Identity Pool role. You will then have the option of adding CRUD (Create, Update, Read and Delete) based permissions as well, so that Authenticated and Guest users will be granted limited permissions within these levels. Even after adding this configuration via the CLI, all Storage access is still public
by default. To guard against accidental public access, the Storage access levels must either be configured globally in the configuration, or set within individual method calls. This guide uses the latter approach, setting Storage access to private
per method call.
The ability to independently configure authorization rules for each category allows for more granular control over data access, and adds greater flexibility. For scenarios where authorization patterns must be mixed and matched, configure the access level on individual Storage method calls. For example, you may want to use private
CRUD access on an individual Storage method call for files that should only be accessible by the owner (such as personal files), protected
read access to allow all logged in users to view common files (such as images in a shared photo album), and public
read access to allow all users to view a file (such as a public profile picture).
For more details on how to configure Storage authorization levels, see the Storage documentation. For more on configuring GraphQL API authorization, see the API documentation.
Create a record with an associated file
First create a record via the GraphQL API, then upload the file to Storage, and finally add the association between the record and file. Use the following example with the GraphQL API and Storage categories to create a record and associate the file with the record.
1let song = Song(name: name)2
3guard let imageData = artCover.pngData() else {4 print("Could not get data from UIImage.")5 return6}7
8// Create the song record9let result = try await Amplify.API.mutate(request: .create(song))10guard case .success(var createdSong) = result else {11 print("Failed with error: ", result)12 return13}14
15// Upload the art cover image16_ = try await Amplify.Storage.uploadData(key: createdSong.id,17 data: imageData,18 options: .init(accessLevel: .private)).value19
20// Update the song record with the image key21createdSong.coverArtKey = createdSong.id22let updateResult = try await Amplify.API.mutate(request: .update(createdSong))23guard case .success(let updatedSong) = updateResult else {24 print("Failed with error: ", updateResult)25 return26}
Add or update a file for an associated record
To associate a new or different file with the record, update the existing record with the file key. The following example uploads the file using Storage and updates the record with the file's key. If an image is already associated with the record, this will update the record with the new image.
1// Upload the new art image2_ = try await Amplify.Storage.uploadData(key: currentSong.id,3 data: imageData,4 options: .init(accessLevel: .private)).value5
6// Update the song record7currentSong.coverArtKey = currentSong.id8let result = try await Amplify.API.mutate(request: .update(currentSong))9guard case .success(let updatedSong) = result else {10 print("Failed with error: ", result)11 return12}
Query a record and retrieve the associated file
To retrieve the file associated with a record, first query the record, then use Storage to download the data to display an image:
1// Get the song record2let result = try await Amplify.API.query(request: .get(Song.self, byIdentifier: currentSong.id))3guard case .success(let queriedSong) = result else {4 print("Failed with error: ", result)5 return6}7guard let song = queriedSong else {8 print("Song may have been deleted, no song with id: ", currentSong.id)9 return10}11
12guard let coverArtKey = song.coverArtKey else {13 print("Song does not contain cover art")14 return15}16
17// Download the art cover18let imageData = try await Amplify.Storage.downloadData(key: coverArtKey,19 options: .init(accessLevel: .private)).value20let image = UIImage(data: imageData)
Delete and remove files associated with API records
There are three common deletion workflows when working with Storage files and the GraphQL API:
- Remove the file association, continue to persist both file and record.
- Remove the file association and delete the file.
- Delete both file and record.
Remove the file association, continue to persist both file and record
The following example removes the file association from the record, but does not delete the file from S3 or the record from the DynamoDB instance.
1// Get the song record2let result = try await Amplify.API.mutate(request: .get(Song.self, byIdentifier: currentSong.id))3guard case .success(let queriedSong) = result else {4 print("Failed with error: ", result)5 return6}7guard var song = queriedSong else {8 print("Song may have been deleted, no song by id: ", currentSong.id)9 return10}11guard song.coverArtKey != nil else {12 print("There is no cover art key to remove image association")13 return14}15
16// Set the association to nil and update it17song.coverArtKey = nil18let updateResult = try await Amplify.API.mutate(request: .update(song))19guard case .success(let updatedSong) = updateResult else {20 print("Failed with error: ", result)21 return22}
Remove the file association and delete the file
The following example removes the file from the record, then deletes the file from S3:
1// Get the song record2let result = try await Amplify.API.query(request: .get(Song.self, byIdentifier: currentSong.id))3guard case .success(let queriedSong) = result else {4 print("Failed with error: ", result)5 return6}7guard var song = queriedSong else {8 print("Song may have been deleted, no song by id: ", currentSong.id)9 return10}11guard let coverArtKey = song.coverArtKey else {12 print("There is no cover art key to remove image association")13 return14}15
16// Set the association to nil and update it17song.coverArtKey = nil18let updateResult = try await Amplify.API.mutate(request: .update(song))19guard case .success(let updatedSong) = updateResult else {20 print("Failed with error: ", result)21 return22}23
24// Remove the image25try await Amplify.Storage.remove(key: coverArtKey,26 options: .init(accessLevel: .private))
Delete both file and record
The following example deletes the record from DynamoDB and then deletes the file from S3:
1// Get the song record2let result = try await Amplify.API.mutate(request: .get(Song.self, byIdentifier: currentSong.id))3guard case .success(let queriedSong) = result else {4 print("Failed with error: ", result)5 return6}7guard let song = queriedSong else {8 print("Song may have been deleted, no song by id: ", currentSong.id)9 return10}11
12if let coverArt = song.coverArtKey {13 // Remove the image14 try await Amplify.Storage.remove(key: coverArt,15 options: .init(accessLevel: .private))16}17
18// Delete the song record19let deleteResult = try await Amplify.API.mutate(request: .delete(song))20guard case .success = deleteResult else {21 print("Failed with error: ", deleteResult)22 return23}
Working with multiple files
You may want to add multiple files to a single record, such as a user profile with multiple images. To do this, you can add a list of file keys to the record. The following example adds a list of file keys to a record:
GraphQL schema to associate a data model with multiple files
When prompted after running amplify add api
use the following schema, which can also be found under amplify/backend/api/[name of project]/schema.graphql
:
1type PhotoAlbum @model @auth(rules: [{ allow: public }]) {2 id: ID!3 name: String!4 imageKeys: [String] #Set as optional to allow adding file(s) after initial create5}
CRUD operations when working with multiple files is the same as when working with a single file, with the exception that we are now working with a list of image keys, as opposed to a single image key.
Create a record with multiple associated files
First create a record via the GraphQL API, then upload the files to Storage, and finally add the associations between the record and files.
1// Create the photo album record2let album = PhotoAlbum(name: name)3let result = try await Amplify.API.mutate(request: .create(album))4guard case .success(var createdAlbum) = result else {5 print("Failed with error: ", result)6 return7}8
9// Upload the photo album images10let imageKeys = await withTaskGroup(of: String?.self) { group in11 for imageData in imagesData {12 group.addTask {13 let key = "\(album.id)-\(UUID().uuidString)"14 do {15 _ = try await Amplify.Storage.uploadData(key: key,16 data: imageData,17 options: .init(accessLevel: .private)).value18 return key19 } catch {20 print("Failed with error:", error)21 return nil22 }23 }24 }25
26 var imageKeys: [String?] = []27 for await imageKey in group {28 imageKeys.append(imageKey)29 }30 return imageKeys.compactMap { $0 }31}32
33// Update the album with the image keys34createdAlbum.imageKeys = imageKeys35let updateResult = try await Amplify.API.mutate(request: .update(createdAlbum))36guard case .success(let updatedAlbum) = updateResult else {37 print("Failed with error: ", updateResult)38 return39}
Create a record with a single associated file
When a schema allows for multiple associated images, you can still create a record with a single associated file.
1// Create the photo album record2let album = PhotoAlbum(name: name)3let result = try await Amplify.API.mutate(request: .create(album))4guard case .success(var createdAlbum) = result else {5 print("Failed with error: ", result)6 return7}8
9// Upload the photo album image10let key = "\(album.id)-\(UUID().uuidString)"11_ = try await Amplify.Storage.uploadData(key: key,12 data: imageData,13 options: .init(accessLevel: .private)).value14
15// Update the album with the image key16createdAlbum.imageKeys = [key]17let updateResult = try await Amplify.API.mutate(request: .update(createdAlbum))18guard case .success(let updatedAlbum) = updateResult else {19 print("Failed with error: ", updateResult)20 return21}
Add new files to an associated record
To associate additional files with a record, update the record with the keys returned by the Storage uploads.
1// Upload the new photo album image2let key = "\(currentAlbum.id)-\(UUID().uuidString)"3_ = try await Amplify.Storage.uploadData(key: key,4 data: imageData,5 options: .init(accessLevel: .private)).value6
7// Get the latest album8let result = try await Amplify.API.query(request: .get(PhotoAlbum.self, byIdentifier: currentAlbum.id))9guard case .success(let queriedAlbum) = result else {10 print("Failed with error: ", result)11 return12}13guard var album = queriedAlbum else {14 print("Album may have been deleted, no album with id: ", currentAlbum.id)15 return16}17
18guard var imageKeys = album.imageKeys else {19 print("Album does not contain images")20 return21}22
23// Add new to the existing keys24imageKeys.append(key)25
26// Update the album with the image keys27album.imageKeys = imageKeys28let updateResult = try await Amplify.API.mutate(request: .update(album))29guard case .success(let updatedAlbum) = updateResult else {30 print("Failed with error: ", updateResult)31 return32}
Update the file for an associated record
Updating a file for an associated record is the same as updating a file for a single file record, with the exception that you will need to update the list of file keys. The following replaces the last image in the album with a new image.
1// Upload the new photo album image2let key = "\(currentAlbum.id)-\(UUID().uuidString)"3_ = try await Amplify.Storage.uploadData(key: key,4 data: imageData,5 options: .init(accessLevel: .private)).value6
7// Update the album with the image keys8var album = currentAlbum9if var imageKeys = album.imageKeys {10 imageKeys.removeLast()11 imageKeys.append(key)12 album.imageKeys = imageKeys13} else {14 album.imageKeys = [key]15}16let updateResult = try await Amplify.API.mutate(request: .update(album))17guard case .success(let updatedAlbum) = updateResult else {18 print("Failed with error: ", updateResult)19 return20}
Query a record and retrieve the associated files
To retrieve the files associated with a record, first query the record, then use Storage to retrieve all the images.
1// Get the song record2let result = try await Amplify.API.query(request: .get(PhotoAlbum.self, byIdentifier: currentAlbum.id))3guard case .success(let queriedAlbum) = result else {4 print("Failed with error: ", result)5 return6}7guard let album = queriedAlbum else {8 print("Album may have been deleted, no album with id: ", currentAlbum.id)9 return10}11
12guard let imageKeysOptional = album.imageKeys else {13 print("Album does not contain images")14 return15}16let imageKeys = imageKeysOptional.compactMap { $0 }17
18// Download the photos19let images = await withTaskGroup(of: UIImage?.self) { group in20 for key in imageKeys {21 group.addTask {22 do {23 let imageData = try await Amplify.Storage.downloadData(key: key,24 options: .init(accessLevel: .private)).value25 return UIImage(data: imageData)26 } catch {27 print("Failed with error:", error)28 return nil29 }30 }31 }32
33 var images: [UIImage?] = []34 for await image in group {35 images.append(image)36 }37 return images.compactMap { $0 }38}
Delete and remove files associated with API records
The workflow for deleting and removing files associated with API records is the same as when working with a single file, except that when performing a delete you will need to iterate over the list of files keys and call Storage.remove()
for each file.
Remove the file association, keep the persisted file and record
1// Get the album record2let result = try await Amplify.API.mutate(request: .get(PhotoAlbum.self, byIdentifier: currentAlbum.id))3guard case .success(let queriedAlbum) = result else {4 print("Failed with error: ", result)5 return6}7guard var album = queriedAlbum else {8 print("Song may have been deleted, no song by id: ", currentAlbum.id)9 return10}11guard let imageKeys = album.imageKeys, !imageKeys.isEmpty else {12 print("There are no images to remove association")13 return14}15
16// Set the association to nil and update it17album.imageKeys = nil18let updateResult = try await Amplify.API.mutate(request: .update(album))19guard case .success(let updatedAlbum) = updateResult else {20 print("Failed with error: ", result)21 return22}
Remove the file association and delete the files
1// Get the album record2let result = try await Amplify.API.query(request: .get(PhotoAlbum.self, byIdentifier: currentAlbum.id))3guard case .success(let queriedAlbum) = result else {4 print("Failed with error: ", result)5 return6}7guard let album = queriedAlbum else {8 print("Album may have been deleted, no album with id: ", currentAlbum.id)9 return10}11
12guard let imageKeysOptional = album.imageKeys else {13 print("Album does not contain images")14 return15}16let imageKeys = imageKeysOptional.compactMap { $0 }17
18// Set the associations to nil and update it19album.imageKeys = nil20let updateResult = try await Amplify.API.mutate(request: .update(album))21guard case .success(let updatedAlbum) = updateResult else {22 print("Failed with error: ", result)23 return24}25
26// Remove the photos27await withTaskGroup(of: Void.self) { group in28 for key in imageKeys {29 group.addTask {30 do {31 try await Amplify.Storage.remove(key: key,32 options: .init(accessLevel: .private))33 } catch {34 print("Failed with error:", error)35 }36 }37 }38
39
40 for await _ in group {41 }42}
Delete the record and all associated files
1// Get the album record2let result = try await Amplify.API.query(request: .get(PhotoAlbum.self, byIdentifier: currentAlbum.id))3guard case .success(let queriedAlbum) = result else {4 print("Failed with error: ", result)5 return6}7guard let album = queriedAlbum else {8 print("Album may have been deleted, no album with id: ", currentAlbum.id)9 return10}11
12guard let imageKeysOptional = album.imageKeys else {13 print("Album does not contain images")14
15 // Delete the album record16 let deleteResult = try await Amplify.API.mutate(request: .delete(album))17 guard case .success = deleteResult else {18 print("Failed with error: ", deleteResult)19 return20 }21 return22}23let imageKeys = imageKeysOptional.compactMap { $0 }24
25// Remove the photos26await withTaskGroup(of: Void.self) { group in27 for key in imageKeys {28 group.addTask {29 do {30 try await Amplify.Storage.remove(key: key,31 options: .init(accessLevel: .private))32 } catch {33 print("Failed with error:", error)34 }35 }36 }37
38
39 for await _ in group {40 }41
42}43
44// Delete the album record45let deleteResult = try await Amplify.API.mutate(request: .delete(album))46guard case .success = deleteResult else {47 print("Failed with error: ", deleteResult)48 return49}
Data consistency when working with records and files
The access patterns in this guide attempt to remove deleted files, but favor leaving orphans over leaving records that point to non-existent files. This optimizes for read latency by ensuring clients rarely attempt to fetch a non-existent file from Storage. However, any app that deletes files can inherently cause records on-device to point to non-existent files.
One example is when we create an API record, associate the Storage file with that record. "Device A" calls the GraphQL API to create API_Record_1
, and then associates that record with First_Photo
. Later, when "Device A" is about to retrieve the file, "Device B" might query API_Record_1
, delete First_Photo
, and update the record accordingly. However, "Device A" is still using the old API_Record_1
, which is now out-of-date. Even though the shared global state is correctly in sync at every stage, the individual device ("Device A") has an out-of-date record that points to a non-existent file. Similar issues can conceivably occur for updates. Depending on your app, some of these mismatches can be minimized even more with real-time data / GraphQL subscriptions.
It is important to understand when these mismatches can occur and to add meaningful error handling around these cases. This guide does not include exhaustive error handling, real-time subscriptions, re-querying of outdated records, or attempts to retry failed operations. However, these are all important considerations for a production-level application.
Complete examples
1import SwiftUI2import Amplify3import AWSAPIPlugin4import AWSCognitoAuthPlugin5import AWSS3StoragePlugin6import Authenticator7import PhotosUI8
9@main10struct WorkingWithFilesApp: App {11
12 init() {13 do {14 Amplify.Logging.logLevel = .verbose15 try Amplify.add(plugin: AWSCognitoAuthPlugin())16 try Amplify.add(plugin: AWSS3StoragePlugin())17 try Amplify.add(plugin: AWSAPIPlugin(modelRegistration: AmplifyModels()))18 try Amplify.configure()19 print("Amplify configured with API, Storage, and Auth plugins!")20 } catch {21 print("Failed to initialize Amplify with \(error)")22 }23 }24
25 var body: some Scene {26 WindowGroup {27 Authenticator { state in28 TabView {29 SongView()30 .tabItem {31 Label("Song", systemImage: "music.note")32 }33
34 PhotoAlbumView()35 .tabItem {36 Label("PhotoAlbum", systemImage: "photo")37 }38 }39
40 }41 }42 }43}44
45struct SignOutButton: View {46 var body: some View {47 Button("Sign out") {48 Task {49 await Amplify.Auth.signOut()50 }51 }.foregroundColor(.black)52 }53}54
55struct TappedButtonStyle: ButtonStyle {56 func makeBody(configuration: Configuration) -> some View {57 configuration.label58 .padding(10)59 .background(configuration.isPressed ? Color.teal.opacity(0.8) : Color.teal)60 .foregroundColor(.white)61 .clipShape(RoundedRectangle(cornerRadius: 10))62 }63}64
65extension Color {66 static let teal = Color(red: 45/255, green: 111/255, blue: 138/255)67}68
69struct DimmedBackgroundView: View {70 var body: some View {71 Color.gray.opacity(0.5)72 .ignoresSafeArea()73 }74}75
76struct ImagePicker: UIViewControllerRepresentable {77 @Binding var selectedImage: UIImage?78 @Environment(\.presentationMode) var presentationMode79
80 class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {81 let parent: ImagePicker82
83 init(_ parent: ImagePicker) {84 self.parent = parent85 }86
87 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {88 if let uiImage = info[.originalImage] as? UIImage {89 parent.selectedImage = uiImage90 }91 parent.presentationMode.wrappedValue.dismiss()92 }93
94 func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {95 parent.presentationMode.wrappedValue.dismiss()96 }97 }98
99 func makeCoordinator() -> Coordinator {100 Coordinator(self)101 }102
103 func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {104 let imagePicker = UIImagePickerController()105 imagePicker.delegate = context.coordinator106 return imagePicker107 }108
109 func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {110 }111}112
113struct MultiImagePicker: UIViewControllerRepresentable {114 @Binding var selectedImages: [UIImage]115
116 func makeUIViewController(context: Context) -> PHPickerViewController {117 var configuration = PHPickerConfiguration()118 configuration.filter = .images119 configuration.selectionLimit = 0120
121 let picker = PHPickerViewController(configuration: configuration)122 picker.delegate = context.coordinator123 return picker124 }125
126 func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {127 // No need for updates in this case128 }129
130 func makeCoordinator() -> Coordinator {131 Coordinator(parent: self)132 }133
134 class Coordinator: PHPickerViewControllerDelegate {135 private let parent: MultiImagePicker136
137 init(parent: MultiImagePicker) {138 self.parent = parent139 }140
141 func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {142 picker.dismiss(animated: true, completion: nil)143 DispatchQueue.main.async {144 self.parent.selectedImages = []145 }146 for result in results {147 if result.itemProvider.canLoadObject(ofClass: UIImage.self) {148 result.itemProvider.loadObject(ofClass: UIImage.self) { (image, error) in149 if let image = image as? UIImage {150 DispatchQueue.main.async {151 self.parent.selectedImages.append(image)152 }153 }154 }155 }156 }157 }158 }159}