Page updated Nov 9, 2023

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.

For more on the Amplify GraphQL API, see the API documentation. For Storage, see Storage documentation. For Auth, see Auth documentation

To get started, go to your project directory and run the command:

amplify add api
1amplify add api

Choose the following when prompted:

? Select from one of the below mentioned services: `GraphQL` ? Choose the default authorization type for the API `Amazon Cognito User Pool` 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.` ? Here is the GraphQL API that we will create. Select a setting to edit or continue `Continue` ? Choose a schema template: `Blank Schema`
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:

type Song @model @auth(rules: [{ allow: public }]) { id: ID! name: String! coverArtKey: String # Set as optional to allow adding file after initial create }
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 create
5}

Add Storage with the command:

amplify add storage
1amplify add storage

Choose the following when prompted:

? Select from one of the below mentioned services: `Content (Images, audio, video, etc.)` ✔ Who should have access: `Auth users only` ✔ What kind of access do you want for Authenticated users? `create/update, read, delete` ✔ Do you want to add a Lambda Trigger for your S3 Bucket? (y/N) · `no`
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)

For the complete working example, including required imports, obtaining the file from the user, and SwiftUI components, see the Complete Example below.

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.

Make sure that the file key used for Storage is unique. In this case, the API record's id is used as the file key for Storage to ensure uniqueness so that multiple API records will not be associated with the same file key unintentionally. However, this may not be true if the API record's id is customized to be a combination of two or more fields, or a different primary key field is used.

let song = Song(name: name) guard let imageData = artCover.pngData() else { print("Could not get data from UIImage.") return } // Create the song record let result = try await Amplify.API.mutate(request: .create(song)) guard case .success(var createdSong) = result else { print("Failed with error: ", result) return } // Upload the art cover image _ = try await Amplify.Storage.uploadData(key: createdSong.id, data: imageData, options: .init(accessLevel: .private)).value // Update the song record with the image key createdSong.coverArtKey = createdSong.id let updateResult = try await Amplify.API.mutate(request: .update(createdSong)) guard case .success(let updatedSong) = updateResult else { print("Failed with error: ", updateResult) return }
1let song = Song(name: name)
2
3guard let imageData = artCover.pngData() else {
4 print("Could not get data from UIImage.")
5 return
6}
7
8// Create the song record
9let result = try await Amplify.API.mutate(request: .create(song))
10guard case .success(var createdSong) = result else {
11 print("Failed with error: ", result)
12 return
13}
14
15// Upload the art cover image
16_ = try await Amplify.Storage.uploadData(key: createdSong.id,
17 data: imageData,
18 options: .init(accessLevel: .private)).value
19
20// Update the song record with the image key
21createdSong.coverArtKey = createdSong.id
22let updateResult = try await Amplify.API.mutate(request: .update(createdSong))
23guard case .success(let updatedSong) = updateResult else {
24 print("Failed with error: ", updateResult)
25 return
26}

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.

// Upload the new art image _ = try await Amplify.Storage.uploadData(key: currentSong.id, data: imageData, options: .init(accessLevel: .private)).value // Update the song record currentSong.coverArtKey = currentSong.id let result = try await Amplify.API.mutate(request: .update(currentSong)) guard case .success(let updatedSong) = result else { print("Failed with error: ", result) return }
1// Upload the new art image
2_ = try await Amplify.Storage.uploadData(key: currentSong.id,
3 data: imageData,
4 options: .init(accessLevel: .private)).value
5
6// Update the song record
7currentSong.coverArtKey = currentSong.id
8let result = try await Amplify.API.mutate(request: .update(currentSong))
9guard case .success(let updatedSong) = result else {
10 print("Failed with error: ", result)
11 return
12}

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:

// Get the song record let result = try await Amplify.API.query(request: .get(Song.self, byIdentifier: currentSong.id)) guard case .success(let queriedSong) = result else { print("Failed with error: ", result) return } guard let song = queriedSong else { print("Song may have been deleted, no song with id: ", currentSong.id) return } guard let coverArtKey = song.coverArtKey else { print("Song does not contain cover art") return } // Download the art cover let imageData = try await Amplify.Storage.downloadData(key: coverArtKey, options: .init(accessLevel: .private)).value let image = UIImage(data: imageData)
1// Get the song record
2let 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 return
6}
7guard let song = queriedSong else {
8 print("Song may have been deleted, no song with id: ", currentSong.id)
9 return
10}
11
12guard let coverArtKey = song.coverArtKey else {
13 print("Song does not contain cover art")
14 return
15}
16
17// Download the art cover
18let imageData = try await Amplify.Storage.downloadData(key: coverArtKey,
19 options: .init(accessLevel: .private)).value
20let 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:

  1. Remove the file association, continue to persist both file and record.
  2. Remove the file association and delete the file.
  3. 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.

// Get the song record let result = try await Amplify.API.mutate(request: .get(Song.self, byIdentifier: currentSong.id)) guard case .success(let queriedSong) = result else { print("Failed with error: ", result) return } guard var song = queriedSong else { print("Song may have been deleted, no song by id: ", currentSong.id) return } guard song.coverArtKey != nil else { print("There is no cover art key to remove image association") return } // Set the association to nil and update it song.coverArtKey = nil let updateResult = try await Amplify.API.mutate(request: .update(song)) guard case .success(let updatedSong) = updateResult else { print("Failed with error: ", result) return }
1// Get the song record
2let 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 return
6}
7guard var song = queriedSong else {
8 print("Song may have been deleted, no song by id: ", currentSong.id)
9 return
10}
11guard song.coverArtKey != nil else {
12 print("There is no cover art key to remove image association")
13 return
14}
15
16// Set the association to nil and update it
17song.coverArtKey = nil
18let updateResult = try await Amplify.API.mutate(request: .update(song))
19guard case .success(let updatedSong) = updateResult else {
20 print("Failed with error: ", result)
21 return
22}

Remove the file association and delete the file

The following example removes the file from the record, then deletes the file from S3:

// Get the song record let result = try await Amplify.API.query(request: .get(Song.self, byIdentifier: currentSong.id)) guard case .success(let queriedSong) = result else { print("Failed with error: ", result) return } guard var song = queriedSong else { print("Song may have been deleted, no song by id: ", currentSong.id) return } guard let coverArtKey = song.coverArtKey else { print("There is no cover art key to remove image association") return } // Set the association to nil and update it song.coverArtKey = nil let updateResult = try await Amplify.API.mutate(request: .update(song)) guard case .success(let updatedSong) = updateResult else { print("Failed with error: ", result) return } // Remove the image try await Amplify.Storage.remove(key: coverArtKey, options: .init(accessLevel: .private))
1// Get the song record
2let 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 return
6}
7guard var song = queriedSong else {
8 print("Song may have been deleted, no song by id: ", currentSong.id)
9 return
10}
11guard let coverArtKey = song.coverArtKey else {
12 print("There is no cover art key to remove image association")
13 return
14}
15
16// Set the association to nil and update it
17song.coverArtKey = nil
18let updateResult = try await Amplify.API.mutate(request: .update(song))
19guard case .success(let updatedSong) = updateResult else {
20 print("Failed with error: ", result)
21 return
22}
23
24// Remove the image
25try 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:

// Get the song record let result = try await Amplify.API.mutate(request: .get(Song.self, byIdentifier: currentSong.id)) guard case .success(let queriedSong) = result else { print("Failed with error: ", result) return } guard let song = queriedSong else { print("Song may have been deleted, no song by id: ", currentSong.id) return } if let coverArt = song.coverArtKey { // Remove the image try await Amplify.Storage.remove(key: coverArt, options: .init(accessLevel: .private)) } // Delete the song record let deleteResult = try await Amplify.API.mutate(request: .delete(song)) guard case .success = deleteResult else { print("Failed with error: ", deleteResult) return }
1// Get the song record
2let 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 return
6}
7guard let song = queriedSong else {
8 print("Song may have been deleted, no song by id: ", currentSong.id)
9 return
10}
11
12if let coverArt = song.coverArtKey {
13 // Remove the image
14 try await Amplify.Storage.remove(key: coverArt,
15 options: .init(accessLevel: .private))
16}
17
18// Delete the song record
19let deleteResult = try await Amplify.API.mutate(request: .delete(song))
20guard case .success = deleteResult else {
21 print("Failed with error: ", deleteResult)
22 return
23}

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:

type PhotoAlbum @model @auth(rules: [{ allow: public }]) { id: ID! name: String! imageKeys: [String] #Set as optional to allow adding file(s) after initial create }
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 create
5}

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.

// Create the photo album record let album = PhotoAlbum(name: name) let result = try await Amplify.API.mutate(request: .create(album)) guard case .success(var createdAlbum) = result else { print("Failed with error: ", result) return } // Upload the photo album images let imageKeys = await withTaskGroup(of: String?.self) { group in for imageData in imagesData { group.addTask { let key = "\(album.id)-\(UUID().uuidString)" do { _ = try await Amplify.Storage.uploadData(key: key, data: imageData, options: .init(accessLevel: .private)).value return key } catch { print("Failed with error:", error) return nil } } } var imageKeys: [String?] = [] for await imageKey in group { imageKeys.append(imageKey) } return imageKeys.compactMap { $0 } } // Update the album with the image keys createdAlbum.imageKeys = imageKeys let updateResult = try await Amplify.API.mutate(request: .update(createdAlbum)) guard case .success(let updatedAlbum) = updateResult else { print("Failed with error: ", updateResult) return }
1// Create the photo album record
2let 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 return
7}
8
9// Upload the photo album images
10let imageKeys = await withTaskGroup(of: String?.self) { group in
11 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)).value
18 return key
19 } catch {
20 print("Failed with error:", error)
21 return nil
22 }
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 keys
34createdAlbum.imageKeys = imageKeys
35let updateResult = try await Amplify.API.mutate(request: .update(createdAlbum))
36guard case .success(let updatedAlbum) = updateResult else {
37 print("Failed with error: ", updateResult)
38 return
39}

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.

// Create the photo album record let album = PhotoAlbum(name: name) let result = try await Amplify.API.mutate(request: .create(album)) guard case .success(var createdAlbum) = result else { print("Failed with error: ", result) return } // Upload the photo album image let key = "\(album.id)-\(UUID().uuidString)" _ = try await Amplify.Storage.uploadData(key: key, data: imageData, options: .init(accessLevel: .private)).value // Update the album with the image key createdAlbum.imageKeys = [key] let updateResult = try await Amplify.API.mutate(request: .update(createdAlbum)) guard case .success(let updatedAlbum) = updateResult else { print("Failed with error: ", updateResult) return }
1// Create the photo album record
2let 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 return
7}
8
9// Upload the photo album image
10let key = "\(album.id)-\(UUID().uuidString)"
11_ = try await Amplify.Storage.uploadData(key: key,
12 data: imageData,
13 options: .init(accessLevel: .private)).value
14
15// Update the album with the image key
16createdAlbum.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 return
21}

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.

// Upload the new photo album image let key = "\(currentAlbum.id)-\(UUID().uuidString)" _ = try await Amplify.Storage.uploadData(key: key, data: imageData, options: .init(accessLevel: .private)).value // Get the latest album let result = try await Amplify.API.query(request: .get(PhotoAlbum.self, byIdentifier: currentAlbum.id)) guard case .success(let queriedAlbum) = result else { print("Failed with error: ", result) return } guard var album = queriedAlbum else { print("Album may have been deleted, no album with id: ", currentAlbum.id) return } guard var imageKeys = album.imageKeys else { print("Album does not contain images") return } // Add new to the existing keys imageKeys.append(key) // Update the album with the image keys album.imageKeys = imageKeys let updateResult = try await Amplify.API.mutate(request: .update(album)) guard case .success(let updatedAlbum) = updateResult else { print("Failed with error: ", updateResult) return }
1// Upload the new photo album image
2let key = "\(currentAlbum.id)-\(UUID().uuidString)"
3_ = try await Amplify.Storage.uploadData(key: key,
4 data: imageData,
5 options: .init(accessLevel: .private)).value
6
7// Get the latest album
8let 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 return
12}
13guard var album = queriedAlbum else {
14 print("Album may have been deleted, no album with id: ", currentAlbum.id)
15 return
16}
17
18guard var imageKeys = album.imageKeys else {
19 print("Album does not contain images")
20 return
21}
22
23// Add new to the existing keys
24imageKeys.append(key)
25
26// Update the album with the image keys
27album.imageKeys = imageKeys
28let updateResult = try await Amplify.API.mutate(request: .update(album))
29guard case .success(let updatedAlbum) = updateResult else {
30 print("Failed with error: ", updateResult)
31 return
32}

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.

// Upload the new photo album image let key = "\(currentAlbum.id)-\(UUID().uuidString)" _ = try await Amplify.Storage.uploadData(key: key, data: imageData, options: .init(accessLevel: .private)).value // Update the album with the image keys var album = currentAlbum if var imageKeys = album.imageKeys { imageKeys.removeLast() imageKeys.append(key) album.imageKeys = imageKeys } else { album.imageKeys = [key] } let updateResult = try await Amplify.API.mutate(request: .update(album)) guard case .success(let updatedAlbum) = updateResult else { print("Failed with error: ", updateResult) return }
1// Upload the new photo album image
2let key = "\(currentAlbum.id)-\(UUID().uuidString)"
3_ = try await Amplify.Storage.uploadData(key: key,
4 data: imageData,
5 options: .init(accessLevel: .private)).value
6
7// Update the album with the image keys
8var album = currentAlbum
9if var imageKeys = album.imageKeys {
10 imageKeys.removeLast()
11 imageKeys.append(key)
12 album.imageKeys = imageKeys
13} 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 return
20}

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.

// Get the song record let result = try await Amplify.API.query(request: .get(PhotoAlbum.self, byIdentifier: currentAlbum.id)) guard case .success(let queriedAlbum) = result else { print("Failed with error: ", result) return } guard let album = queriedAlbum else { print("Album may have been deleted, no album with id: ", currentAlbum.id) return } guard let imageKeysOptional = album.imageKeys else { print("Album does not contain images") return } let imageKeys = imageKeysOptional.compactMap { $0 } // Download the photos let images = await withTaskGroup(of: UIImage?.self) { group in for key in imageKeys { group.addTask { do { let imageData = try await Amplify.Storage.downloadData(key: key, options: .init(accessLevel: .private)).value return UIImage(data: imageData) } catch { print("Failed with error:", error) return nil } } } var images: [UIImage?] = [] for await image in group { images.append(image) } return images.compactMap { $0 } }
1// Get the song record
2let 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 return
6}
7guard let album = queriedAlbum else {
8 print("Album may have been deleted, no album with id: ", currentAlbum.id)
9 return
10}
11
12guard let imageKeysOptional = album.imageKeys else {
13 print("Album does not contain images")
14 return
15}
16let imageKeys = imageKeysOptional.compactMap { $0 }
17
18// Download the photos
19let images = await withTaskGroup(of: UIImage?.self) { group in
20 for key in imageKeys {
21 group.addTask {
22 do {
23 let imageData = try await Amplify.Storage.downloadData(key: key,
24 options: .init(accessLevel: .private)).value
25 return UIImage(data: imageData)
26 } catch {
27 print("Failed with error:", error)
28 return nil
29 }
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

// Get the album record let result = try await Amplify.API.mutate(request: .get(PhotoAlbum.self, byIdentifier: currentAlbum.id)) guard case .success(let queriedAlbum) = result else { print("Failed with error: ", result) return } guard var album = queriedAlbum else { print("Song may have been deleted, no song by id: ", currentAlbum.id) return } guard let imageKeys = album.imageKeys, !imageKeys.isEmpty else { print("There are no images to remove association") return } // Set the association to nil and update it album.imageKeys = nil let updateResult = try await Amplify.API.mutate(request: .update(album)) guard case .success(let updatedAlbum) = updateResult else { print("Failed with error: ", result) return }
1// Get the album record
2let 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 return
6}
7guard var album = queriedAlbum else {
8 print("Song may have been deleted, no song by id: ", currentAlbum.id)
9 return
10}
11guard let imageKeys = album.imageKeys, !imageKeys.isEmpty else {
12 print("There are no images to remove association")
13 return
14}
15
16// Set the association to nil and update it
17album.imageKeys = nil
18let updateResult = try await Amplify.API.mutate(request: .update(album))
19guard case .success(let updatedAlbum) = updateResult else {
20 print("Failed with error: ", result)
21 return
22}

Remove the file association and delete the files

// Get the album record let result = try await Amplify.API.query(request: .get(PhotoAlbum.self, byIdentifier: currentAlbum.id)) guard case .success(let queriedAlbum) = result else { print("Failed with error: ", result) return } guard let album = queriedAlbum else { print("Album may have been deleted, no album with id: ", currentAlbum.id) return } guard let imageKeysOptional = album.imageKeys else { print("Album does not contain images") return } let imageKeys = imageKeysOptional.compactMap { $0 } // Set the associations to nil and update it album.imageKeys = nil let updateResult = try await Amplify.API.mutate(request: .update(album)) guard case .success(let updatedAlbum) = updateResult else { print("Failed with error: ", result) return } // Remove the photos await withTaskGroup(of: Void.self) { group in for key in imageKeys { group.addTask { do { try await Amplify.Storage.remove(key: key, options: .init(accessLevel: .private)) } catch { print("Failed with error:", error) } } } for await _ in group { } }
1// Get the album record
2let 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 return
6}
7guard let album = queriedAlbum else {
8 print("Album may have been deleted, no album with id: ", currentAlbum.id)
9 return
10}
11
12guard let imageKeysOptional = album.imageKeys else {
13 print("Album does not contain images")
14 return
15}
16let imageKeys = imageKeysOptional.compactMap { $0 }
17
18// Set the associations to nil and update it
19album.imageKeys = nil
20let updateResult = try await Amplify.API.mutate(request: .update(album))
21guard case .success(let updatedAlbum) = updateResult else {
22 print("Failed with error: ", result)
23 return
24}
25
26// Remove the photos
27await withTaskGroup(of: Void.self) { group in
28 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

// Get the album record let result = try await Amplify.API.query(request: .get(PhotoAlbum.self, byIdentifier: currentAlbum.id)) guard case .success(let queriedAlbum) = result else { print("Failed with error: ", result) return } guard let album = queriedAlbum else { print("Album may have been deleted, no album with id: ", currentAlbum.id) return } guard let imageKeysOptional = album.imageKeys else { print("Album does not contain images") // Delete the album record let deleteResult = try await Amplify.API.mutate(request: .delete(album)) guard case .success = deleteResult else { print("Failed with error: ", deleteResult) return } return } let imageKeys = imageKeysOptional.compactMap { $0 } // Remove the photos await withTaskGroup(of: Void.self) { group in for key in imageKeys { group.addTask { do { try await Amplify.Storage.remove(key: key, options: .init(accessLevel: .private)) } catch { print("Failed with error:", error) } } } for await _ in group { } } // Delete the album record let deleteResult = try await Amplify.API.mutate(request: .delete(album)) guard case .success = deleteResult else { print("Failed with error: ", deleteResult) return }
1// Get the album record
2let 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 return
6}
7guard let album = queriedAlbum else {
8 print("Album may have been deleted, no album with id: ", currentAlbum.id)
9 return
10}
11
12guard let imageKeysOptional = album.imageKeys else {
13 print("Album does not contain images")
14
15 // Delete the album record
16 let deleteResult = try await Amplify.API.mutate(request: .delete(album))
17 guard case .success = deleteResult else {
18 print("Failed with error: ", deleteResult)
19 return
20 }
21 return
22}
23let imageKeys = imageKeysOptional.compactMap { $0 }
24
25// Remove the photos
26await withTaskGroup(of: Void.self) { group in
27 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 record
45let deleteResult = try await Amplify.API.mutate(request: .delete(album))
46guard case .success = deleteResult else {
47 print("Failed with error: ", deleteResult)
48 return
49}

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

import SwiftUI import Amplify import AWSAPIPlugin import AWSCognitoAuthPlugin import AWSS3StoragePlugin import Authenticator import PhotosUI @main struct WorkingWithFilesApp: App { init() { do { Amplify.Logging.logLevel = .verbose try Amplify.add(plugin: AWSCognitoAuthPlugin()) try Amplify.add(plugin: AWSS3StoragePlugin()) try Amplify.add(plugin: AWSAPIPlugin(modelRegistration: AmplifyModels())) try Amplify.configure() print("Amplify configured with API, Storage, and Auth plugins!") } catch { print("Failed to initialize Amplify with \(error)") } } var body: some Scene { WindowGroup { Authenticator { state in TabView { SongView() .tabItem { Label("Song", systemImage: "music.note") } PhotoAlbumView() .tabItem { Label("PhotoAlbum", systemImage: "photo") } } } } } } struct SignOutButton: View { var body: some View { Button("Sign out") { Task { await Amplify.Auth.signOut() } }.foregroundColor(.black) } } struct TappedButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .padding(10) .background(configuration.isPressed ? Color.teal.opacity(0.8) : Color.teal) .foregroundColor(.white) .clipShape(RoundedRectangle(cornerRadius: 10)) } } extension Color { static let teal = Color(red: 45/255, green: 111/255, blue: 138/255) } struct DimmedBackgroundView: View { var body: some View { Color.gray.opacity(0.5) .ignoresSafeArea() } } struct ImagePicker: UIViewControllerRepresentable { @Binding var selectedImage: UIImage? @Environment(\.presentationMode) var presentationMode class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate { let parent: ImagePicker init(_ parent: ImagePicker) { self.parent = parent } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { if let uiImage = info[.originalImage] as? UIImage { parent.selectedImage = uiImage } parent.presentationMode.wrappedValue.dismiss() } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { parent.presentationMode.wrappedValue.dismiss() } } func makeCoordinator() -> Coordinator { Coordinator(self) } func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController { let imagePicker = UIImagePickerController() imagePicker.delegate = context.coordinator return imagePicker } func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) { } } struct MultiImagePicker: UIViewControllerRepresentable { @Binding var selectedImages: [UIImage] func makeUIViewController(context: Context) -> PHPickerViewController { var configuration = PHPickerConfiguration() configuration.filter = .images configuration.selectionLimit = 0 let picker = PHPickerViewController(configuration: configuration) picker.delegate = context.coordinator return picker } func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) { // No need for updates in this case } func makeCoordinator() -> Coordinator { Coordinator(parent: self) } class Coordinator: PHPickerViewControllerDelegate { private let parent: MultiImagePicker init(parent: MultiImagePicker) { self.parent = parent } func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) { picker.dismiss(animated: true, completion: nil) DispatchQueue.main.async { self.parent.selectedImages = [] } for result in results { if result.itemProvider.canLoadObject(ofClass: UIImage.self) { result.itemProvider.loadObject(ofClass: UIImage.self) { (image, error) in if let image = image as? UIImage { DispatchQueue.main.async { self.parent.selectedImages.append(image) } } } } } } } }
1import SwiftUI
2import Amplify
3import AWSAPIPlugin
4import AWSCognitoAuthPlugin
5import AWSS3StoragePlugin
6import Authenticator
7import PhotosUI
8
9@main
10struct WorkingWithFilesApp: App {
11
12 init() {
13 do {
14 Amplify.Logging.logLevel = .verbose
15 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 in
28 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.label
58 .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 presentationMode
79
80 class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
81 let parent: ImagePicker
82
83 init(_ parent: ImagePicker) {
84 self.parent = parent
85 }
86
87 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
88 if let uiImage = info[.originalImage] as? UIImage {
89 parent.selectedImage = uiImage
90 }
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.coordinator
106 return imagePicker
107 }
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 = .images
119 configuration.selectionLimit = 0
120
121 let picker = PHPickerViewController(configuration: configuration)
122 picker.delegate = context.coordinator
123 return picker
124 }
125
126 func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {
127 // No need for updates in this case
128 }
129
130 func makeCoordinator() -> Coordinator {
131 Coordinator(parent: self)
132 }
133
134 class Coordinator: PHPickerViewControllerDelegate {
135 private let parent: MultiImagePicker
136
137 init(parent: MultiImagePicker) {
138 self.parent = parent
139 }
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) in
149 if let image = image as? UIImage {
150 DispatchQueue.main.async {
151 self.parent.selectedImages.append(image)
152 }
153 }
154 }
155 }
156 }
157 }
158 }
159}