Ejemplos de Amazon S3 que utilizan SDK Swift - AWS SDKEjemplos de código

Hay más AWS SDK ejemplos disponibles en el GitHub repositorio de AWS Doc SDK Examples.

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Ejemplos de Amazon S3 que utilizan SDK Swift

Los siguientes ejemplos de código muestran cómo realizar acciones e implementar escenarios comunes mediante el uso AWS SDK de Swift con Amazon S3.

Los conceptos básicos son ejemplos de código que muestran cómo realizar las operaciones esenciales dentro de un servicio.

Las acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Mientras las acciones muestran cómo llamar a las funciones de servicio individuales, es posible ver las acciones en contexto en los escenarios relacionados.

Cada ejemplo incluye un enlace al código fuente completo, donde puede encontrar instrucciones sobre cómo configurar y ejecutar el código en su contexto.

Conceptos básicos

En el siguiente ejemplo de código, se muestra cómo:

  • Creación de un bucket y cargar un archivo en el bucket.

  • Descargar un objeto desde un bucket.

  • Copiar un objeto en una subcarpeta de un bucket.

  • Obtención de una lista de los objetos de un bucket.

  • Eliminación del bucket y todos los objetos que incluye.

SDKpara Swift
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import AWSS3 import Foundation import AWSS3 import Smithy import ClientRuntime /// A class containing all the code that interacts with the AWS SDK for Swift. public class ServiceHandler { let configuration: S3Client.S3ClientConfiguration let client: S3Client enum HandlerError: Error { case getObjectBody(String) case readGetObjectBody(String) case missingContents(String) } /// Initialize and return a new ``ServiceHandler`` object, which is used to drive the AWS calls /// used for the example. /// /// - Returns: A new ``ServiceHandler`` object, ready to be called to /// execute AWS operations. public init() async throws { do { configuration = try await S3Client.S3ClientConfiguration() // configuration.region = "us-east-2" // Uncomment this to set the region programmatically. client = S3Client(config: configuration) } catch { print("ERROR: ", dump(error, name: "Initializing S3 client")) throw error } } /// Create a new user given the specified name. /// /// - Parameters: /// - name: Name of the bucket to create. /// Throws an exception if an error occurs. public func createBucket(name: String) async throws { var input = CreateBucketInput( bucket: name ) // For regions other than "us-east-1", you must set the locationConstraint in the createBucketConfiguration. // For more information, see LocationConstraint in the S3 API guide. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html#API_CreateBucket_RequestBody if let region = configuration.region { if region != "us-east-1" { input.createBucketConfiguration = S3ClientTypes.CreateBucketConfiguration(locationConstraint: S3ClientTypes.BucketLocationConstraint(rawValue: region)) } } do { _ = try await client.createBucket(input: input) } catch let error as BucketAlreadyOwnedByYou { print("The bucket '\(name)' already exists and is owned by you. You may wish to ignore this exception.") throw error } catch { print("ERROR: ", dump(error, name: "Creating a bucket")) throw error } } /// Delete a bucket. /// - Parameter name: Name of the bucket to delete. public func deleteBucket(name: String) async throws { let input = DeleteBucketInput( bucket: name ) do { _ = try await client.deleteBucket(input: input) } catch { print("ERROR: ", dump(error, name: "Deleting a bucket")) throw error } } /// Upload a file from local storage to the bucket. /// - Parameters: /// - bucket: Name of the bucket to upload the file to. /// - key: Name of the file to create. /// - file: Path name of the file to upload. public func uploadFile(bucket: String, key: String, file: String) async throws { let fileUrl = URL(fileURLWithPath: file) do { let fileData = try Data(contentsOf: fileUrl) let dataStream = ByteStream.data(fileData) let input = PutObjectInput( body: dataStream, bucket: bucket, key: key ) _ = try await client.putObject(input: input) } catch { print("ERROR: ", dump(error, name: "Putting an object.")) throw error } } /// Create a file in the specified bucket with the given name. The new /// file's contents are uploaded from a `Data` object. /// /// - Parameters: /// - bucket: Name of the bucket to create a file in. /// - key: Name of the file to create. /// - data: A `Data` object to write into the new file. public func createFile(bucket: String, key: String, withData data: Data) async throws { let dataStream = ByteStream.data(data) let input = PutObjectInput( body: dataStream, bucket: bucket, key: key ) do { _ = try await client.putObject(input: input) } catch { print("ERROR: ", dump(error, name: "Putting an object.")) throw error } } /// Download the named file to the given directory on the local device. /// /// - Parameters: /// - bucket: Name of the bucket that contains the file to be copied. /// - key: The name of the file to copy from the bucket. /// - to: The path of the directory on the local device where you want to /// download the file. public func downloadFile(bucket: String, key: String, to: String) async throws { let fileUrl = URL(fileURLWithPath: to).appendingPathComponent(key) let input = GetObjectInput( bucket: bucket, key: key ) do { let output = try await client.getObject(input: input) guard let body = output.body else { throw HandlerError.getObjectBody("GetObjectInput missing body.") } guard let data = try await body.readData() else { throw HandlerError.readGetObjectBody("GetObjectInput unable to read data.") } try data.write(to: fileUrl) } catch { print("ERROR: ", dump(error, name: "Downloading a file.")) throw error } } /// Read the specified file from the given S3 bucket into a Swift /// `Data` object. /// /// - Parameters: /// - bucket: Name of the bucket containing the file to read. /// - key: Name of the file within the bucket to read. /// /// - Returns: A `Data` object containing the complete file data. public func readFile(bucket: String, key: String) async throws -> Data { let input = GetObjectInput( bucket: bucket, key: key ) do { let output = try await client.getObject(input: input) guard let body = output.body else { throw HandlerError.getObjectBody("GetObjectInput missing body.") } guard let data = try await body.readData() else { throw HandlerError.readGetObjectBody("GetObjectInput unable to read data.") } return data } catch { print("ERROR: ", dump(error, name: "Reading a file.")) throw error } } /// Copy a file from one bucket to another. /// /// - Parameters: /// - sourceBucket: Name of the bucket containing the source file. /// - name: Name of the source file. /// - destBucket: Name of the bucket to copy the file into. public func copyFile(from sourceBucket: String, name: String, to destBucket: String) async throws { let srcUrl = ("\(sourceBucket)/\(name)").addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) let input = CopyObjectInput( bucket: destBucket, copySource: srcUrl, key: name ) do { _ = try await client.copyObject(input: input) } catch { print("ERROR: ", dump(error, name: "Copying an object.")) throw error } } /// Deletes the specified file from Amazon S3. /// /// - Parameters: /// - bucket: Name of the bucket containing the file to delete. /// - key: Name of the file to delete. /// public func deleteFile(bucket: String, key: String) async throws { let input = DeleteObjectInput( bucket: bucket, key: key ) do { _ = try await client.deleteObject(input: input) } catch { print("ERROR: ", dump(error, name: "Deleting a file.")) throw error } } /// Returns an array of strings, each naming one file in the /// specified bucket. /// /// - Parameter bucket: Name of the bucket to get a file listing for. /// - Returns: An array of `String` objects, each giving the name of /// one file contained in the bucket. public func listBucketFiles(bucket: String) async throws -> [String] { do { let input = ListObjectsV2Input( bucket: bucket ) // Use "Paginated" to get all the objects. // This lets the SDK handle the 'continuationToken' in "ListObjectsV2Output". let output = client.listObjectsV2Paginated(input: input) var names: [String] = [] for try await page in output { guard let objList = page.contents else { print("ERROR: listObjectsV2Paginated returned nil contents.") continue } for obj in objList { if let objName = obj.key { names.append(objName) } } } return names } catch { print("ERROR: ", dump(error, name: "Listing objects.")) throw error } } }
import AWSS3 import Foundation import ServiceHandler import ArgumentParser /// The command-line arguments and options available for this /// example command. struct ExampleCommand: ParsableCommand { @Argument(help: "Name of the S3 bucket to create") var bucketName: String @Argument(help: "Pathname of the file to upload to the S3 bucket") var uploadSource: String @Argument(help: "The name (key) to give the file in the S3 bucket") var objName: String @Argument(help: "S3 bucket to copy the object to") var destBucket: String @Argument(help: "Directory where you want to download the file from the S3 bucket") var downloadDir: String static var configuration = CommandConfiguration( commandName: "s3-basics", abstract: "Demonstrates a series of basic AWS S3 functions.", discussion: """ Performs the following Amazon S3 commands: * `CreateBucket` * `PutObject` * `GetObject` * `CopyObject` * `ListObjects` * `DeleteObjects` * `DeleteBucket` """ ) /// Called by ``main()`` to do the actual running of the AWS /// example. func runAsync() async throws { let serviceHandler = try await ServiceHandler() // 1. Create the bucket. print("Creating the bucket \(bucketName)...") try await serviceHandler.createBucket(name: bucketName) // 2. Upload a file to the bucket. print("Uploading the file \(uploadSource)...") try await serviceHandler.uploadFile(bucket: bucketName, key: objName, file: uploadSource) // 3. Download the file. print("Downloading the file \(objName) to \(downloadDir)...") try await serviceHandler.downloadFile(bucket: bucketName, key: objName, to: downloadDir) // 4. Copy the file to another bucket. print("Copying the file to the bucket \(destBucket)...") try await serviceHandler.copyFile(from: bucketName, name: objName, to: destBucket) // 5. List the contents of the bucket. print("Getting a list of the files in the bucket \(bucketName)") let fileList = try await serviceHandler.listBucketFiles(bucket: bucketName) let numFiles = fileList.count if numFiles != 0 { print("\(numFiles) file\((numFiles > 1) ? "s" : "") in bucket \(bucketName):") for name in fileList { print(" \(name)") } } else { print("No files found in bucket \(bucketName)") } // 6. Delete the objects from the bucket. print("Deleting the file \(objName) from the bucket \(bucketName)...") try await serviceHandler.deleteFile(bucket: bucketName, key: objName) print("Deleting the file \(objName) from the bucket \(destBucket)...") try await serviceHandler.deleteFile(bucket: destBucket, key: objName) // 7. Delete the bucket. print("Deleting the bucket \(bucketName)...") try await serviceHandler.deleteBucket(name: bucketName) print("Done.") } } // // Main program entry point. // @main struct Main { static func main() async { let args = Array(CommandLine.arguments.dropFirst()) do { let command = try ExampleCommand.parse(args) try await command.runAsync() } catch { ExampleCommand.exit(withError: error) } } }

Acciones

En el siguiente ejemplo de código se muestra cómo usar CopyObject.

SDKpara Swift
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import AWSS3 public func copyFile(from sourceBucket: String, name: String, to destBucket: String) async throws { let srcUrl = ("\(sourceBucket)/\(name)").addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) let input = CopyObjectInput( bucket: destBucket, copySource: srcUrl, key: name ) do { _ = try await client.copyObject(input: input) } catch { print("ERROR: ", dump(error, name: "Copying an object.")) throw error } }
  • Para API obtener más información, consulte CopyObject AWSSDKla API referencia de Swift.

En el siguiente ejemplo de código se muestra cómo usar CreateBucket.

SDKpara Swift
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import AWSS3 public func createBucket(name: String) async throws { var input = CreateBucketInput( bucket: name ) // For regions other than "us-east-1", you must set the locationConstraint in the createBucketConfiguration. // For more information, see LocationConstraint in the S3 API guide. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html#API_CreateBucket_RequestBody if let region = configuration.region { if region != "us-east-1" { input.createBucketConfiguration = S3ClientTypes.CreateBucketConfiguration(locationConstraint: S3ClientTypes.BucketLocationConstraint(rawValue: region)) } } do { _ = try await client.createBucket(input: input) } catch let error as BucketAlreadyOwnedByYou { print("The bucket '\(name)' already exists and is owned by you. You may wish to ignore this exception.") throw error } catch { print("ERROR: ", dump(error, name: "Creating a bucket")) throw error } }
  • Para API obtener más información, consulte CreateBucket AWSSDKla API referencia de Swift.

En el siguiente ejemplo de código se muestra cómo usar DeleteBucket.

SDKpara Swift
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import AWSS3 public func deleteBucket(name: String) async throws { let input = DeleteBucketInput( bucket: name ) do { _ = try await client.deleteBucket(input: input) } catch { print("ERROR: ", dump(error, name: "Deleting a bucket")) throw error } }
  • Para API obtener más información, consulte DeleteBucket AWSSDKla API referencia de Swift.

En el siguiente ejemplo de código se muestra cómo usar DeleteObject.

SDKpara Swift
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import AWSS3 public func deleteFile(bucket: String, key: String) async throws { let input = DeleteObjectInput( bucket: bucket, key: key ) do { _ = try await client.deleteObject(input: input) } catch { print("ERROR: ", dump(error, name: "Deleting a file.")) throw error } }
  • Para API obtener más información, consulte DeleteObject AWSSDKla API referencia de Swift.

En el siguiente ejemplo de código se muestra cómo usar DeleteObjects.

SDKpara Swift
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import AWSS3 public func deleteObjects(bucket: String, keys: [String]) async throws { let input = DeleteObjectsInput( bucket: bucket, delete: S3ClientTypes.Delete( objects: keys.map { S3ClientTypes.ObjectIdentifier(key: $0) }, quiet: true ) ) do { _ = try await client.deleteObjects(input: input) } catch { print("ERROR: deleteObjects:", dump(error)) throw error } }
  • Para API obtener más información, consulte DeleteObjects AWSSDKla API referencia de Swift.

En el siguiente ejemplo de código se muestra cómo usar GetObject.

SDKpara Swift
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import AWSS3 public func downloadFile(bucket: String, key: String, to: String) async throws { let fileUrl = URL(fileURLWithPath: to).appendingPathComponent(key) let input = GetObjectInput( bucket: bucket, key: key ) do { let output = try await client.getObject(input: input) guard let body = output.body else { throw HandlerError.getObjectBody("GetObjectInput missing body.") } guard let data = try await body.readData() else { throw HandlerError.readGetObjectBody("GetObjectInput unable to read data.") } try data.write(to: fileUrl) } catch { print("ERROR: ", dump(error, name: "Downloading a file.")) throw error } }
import AWSS3 public func readFile(bucket: String, key: String) async throws -> Data { let input = GetObjectInput( bucket: bucket, key: key ) do { let output = try await client.getObject(input: input) guard let body = output.body else { throw HandlerError.getObjectBody("GetObjectInput missing body.") } guard let data = try await body.readData() else { throw HandlerError.readGetObjectBody("GetObjectInput unable to read data.") } return data } catch { print("ERROR: ", dump(error, name: "Reading a file.")) throw error } }
  • Para API obtener más información, consulte GetObject AWSSDKla API referencia de Swift.

En el siguiente ejemplo de código se muestra cómo usar ListBuckets.

SDKpara Swift
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import AWSS3 /// Return an array containing information about every available bucket. /// /// - Returns: An array of ``S3ClientTypes.Bucket`` objects describing /// each bucket. public func getAllBuckets() async throws -> [S3ClientTypes.Bucket] { return try await client.listBuckets(input: ListBucketsInput()) }
  • Para API obtener más información, consulte ListBuckets AWSSDKla API referencia de Swift.

En el siguiente ejemplo de código se muestra cómo usar ListObjectsV2.

SDKpara Swift
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import AWSS3 public func listBucketFiles(bucket: String) async throws -> [String] { do { let input = ListObjectsV2Input( bucket: bucket ) // Use "Paginated" to get all the objects. // This lets the SDK handle the 'continuationToken' in "ListObjectsV2Output". let output = client.listObjectsV2Paginated(input: input) var names: [String] = [] for try await page in output { guard let objList = page.contents else { print("ERROR: listObjectsV2Paginated returned nil contents.") continue } for obj in objList { if let objName = obj.key { names.append(objName) } } } return names } catch { print("ERROR: ", dump(error, name: "Listing objects.")) throw error } }
  • Para API obtener más información, consulte ListObjectsV2 en AWS SDKpara obtener información sobre Swift API.

En el siguiente ejemplo de código se muestra cómo usar PutObject.

SDKpara Swift
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import AWSS3 import Smithy public func uploadFile(bucket: String, key: String, file: String) async throws { let fileUrl = URL(fileURLWithPath: file) do { let fileData = try Data(contentsOf: fileUrl) let dataStream = ByteStream.data(fileData) let input = PutObjectInput( body: dataStream, bucket: bucket, key: key ) _ = try await client.putObject(input: input) } catch { print("ERROR: ", dump(error, name: "Putting an object.")) throw error } }
import AWSS3 import Smithy public func createFile(bucket: String, key: String, withData data: Data) async throws { let dataStream = ByteStream.data(data) let input = PutObjectInput( body: dataStream, bucket: bucket, key: key ) do { _ = try await client.putObject(input: input) } catch { print("ERROR: ", dump(error, name: "Putting an object.")) throw error } }
  • Para API obtener más información, consulte PutObject AWSSDKla API referencia de Swift.