Ada lebih banyak AWS SDK contoh yang tersedia di GitHub repo SDKContoh AWS Dokumen
Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.
Contoh Amazon S3 menggunakan SDK untuk Swift
Contoh kode berikut menunjukkan cara melakukan tindakan dan menerapkan skenario umum dengan menggunakan AWS SDK for Swift dengan Amazon S3.
Dasar-dasar adalah contoh kode yang menunjukkan kepada Anda bagaimana melakukan operasi penting dalam suatu layanan.
Tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Sementara tindakan menunjukkan cara memanggil fungsi layanan individual, Anda dapat melihat tindakan dalam konteks dalam skenario terkait.
Setiap contoh menyertakan tautan ke kode sumber lengkap, di mana Anda dapat menemukan instruksi tentang cara mengatur dan menjalankan kode dalam konteks.
Hal-hal mendasar
Contoh kode berikut ini menunjukkan cara:
Membuat bucket dan mengunggah file ke dalamnya.
Mengunduh objek dari bucket.
Menyalin objek ke subfolder di bucket.
Membuat daftar objek dalam bucket.
Menghapus objek bucket dan bucket tersebut.
- SDKuntuk Swift
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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) } } }
-
Untuk API detailnya, lihat topik berikut AWS SDKuntuk API referensi Swift.
-
Tindakan
Contoh kode berikut menunjukkan cara menggunakanCopyObject
.
- SDKuntuk Swift
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 } }
-
Untuk API detailnya, lihat CopyObject AWS
SDKAPIreferensi Swift.
-
Contoh kode berikut menunjukkan cara menggunakanCreateBucket
.
- SDKuntuk Swift
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 } }
-
Untuk API detailnya, lihat CreateBucket AWS
SDKAPIreferensi Swift.
-
Contoh kode berikut menunjukkan cara menggunakanDeleteBucket
.
- SDKuntuk Swift
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 } }
-
Untuk API detailnya, lihat DeleteBucket AWS
SDKAPIreferensi Swift.
-
Contoh kode berikut menunjukkan cara menggunakanDeleteObject
.
- SDKuntuk Swift
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 } }
-
Untuk API detailnya, lihat DeleteObject AWS
SDKAPIreferensi Swift.
-
Contoh kode berikut menunjukkan cara menggunakanDeleteObjects
.
- SDKuntuk Swift
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 } }
-
Untuk API detailnya, lihat DeleteObjects AWS
SDKAPIreferensi Swift.
-
Contoh kode berikut menunjukkan cara menggunakanGetObject
.
- SDKuntuk Swift
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 } }
-
Untuk API detailnya, lihat GetObject AWS
SDKAPIreferensi Swift.
-
Contoh kode berikut menunjukkan cara menggunakanListBuckets
.
- SDKuntuk Swift
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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()) }
-
Untuk API detailnya, lihat ListBuckets AWS
SDKAPIreferensi Swift.
-
Contoh kode berikut menunjukkan cara menggunakanListObjectsV2
.
- SDKuntuk Swift
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 } }
-
Untuk API detailnya, lihat ListObjectsV2 AWS
SDKuntuk API referensi Swift.
-
Contoh kode berikut menunjukkan cara menggunakanPutObject
.
- SDKuntuk Swift
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 } }
-
Untuk API detailnya, lihat PutObject AWS
SDKAPIreferensi Swift.
-