aws-sdk-swift-usage
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAWS SDK for Swift
AWS SDK for Swift
Async Code Structure
异步代码结构
All SDK operations are async. Use entry point:
@mainswift
@main
struct Main {
static func main() async throws {
let client = try await S3Client()
// ... async operations
}
}所有SDK操作均为异步。使用作为入口点:
@mainswift
@main
struct Main {
static func main() async throws {
let client = try await S3Client()
// ... async operations
}
}CRITICAL: Use Struct Config Types
重要提示:使用结构体类型的配置
NEVER use or - these are DEPRECATED classes.
S3ClientConfigurationDynamoDBClientConfigurationALWAYS use the struct-based config types:
- (not S3ClientConfiguration)
S3Client.S3ClientConfig - (not DynamoDBClientConfiguration)
DynamoDBClient.DynamoDBClientConfig - (not STSClientConfiguration)
STSClient.STSClientConfig
Config parameters MUST be in declaration order. Region is ALWAYS required when creating a config. Check the service client source for exact order.
swift
// CORRECT - struct config
let config = try await S3Client.S3ClientConfig(region: "us-west-2")
let client = S3Client(config: config)
// WRONG - deprecated class
// let config = try await S3Client.S3ClientConfiguration(region: "us-west-2")切勿使用或——这些是已废弃的类。
S3ClientConfigurationDynamoDBClientConfiguration请始终使用基于结构体的配置类型:
- (而非S3ClientConfiguration)
S3Client.S3ClientConfig - (而非DynamoDBClientConfiguration)
DynamoDBClient.DynamoDBClientConfig - (而非STSClientConfiguration)
STSClient.STSClientConfig
配置参数必须按照声明顺序传入。创建配置时,Region(区域)是必填项。请查看服务客户端源码确认确切的参数顺序。
swift
// 正确用法 - 结构体配置
let config = try await S3Client.S3ClientConfig(region: "us-west-2")
let client = S3Client(config: config)
// 错误用法 - 已废弃的类
// let config = try await S3Client.S3ClientConfiguration(region: "us-west-2")Client Creation
客户端创建
All service clients follow the same pattern: with .
<Service>Client<Service>Client.<Service>ClientConfigModel types (structs/enums used in requests/responses) are namespaced under :
<Service>ClientTypes- ,
S3ClientTypes.BucketS3ClientTypes.Object DynamoDBClientTypes.AttributeValue- ,
CloudWatchClientTypes.MetricDatumCloudWatchClientTypes.Dimension
swift
import AWSS3
import AWSDynamoDB
// Simple - auto-detects region
let s3 = try await S3Client()
let dynamo = try await DynamoDBClient()
// With region
let s3 = try S3Client(region: "us-west-2")
// With config - parameters must be in declaration order
let config = try await S3Client.S3ClientConfig(
useFIPS: true,
awsRetryMode: .adaptive,
maxAttempts: 5,
region: "us-west-2"
)
let client = S3Client(config: config)
// With custom endpoint and credentials
let config = try await S3Client.S3ClientConfig(
awsCredentialIdentityResolver: resolver,
region: "us-west-2",
endpoint: "https://s3.custom-endpoint.com"
)Common config parameters (MUST follow declaration order):
-
- Custom credentials
awsCredentialIdentityResolver -
- Enable FIPS endpoints
useFIPS -
- Enable dual-stack endpoints
useDualStack -
- Retry strategy (.adaptive, .standard, .legacy)
awsRetryMode -
- Max retry attempts
maxAttempts -
- AWS region
region -
- Custom HTTP client (requires HttpClientConfiguration parameter):
httpClientEngineswiftimport ClientRuntime let httpConfig = HttpClientConfiguration() let httpClient = URLSessionHTTPClient(httpClientConfiguration: httpConfig) let config = try await S3Client.S3ClientConfig( region: "us-east-1", httpClientEngine: httpClient ) -
- Custom endpoint URL
endpoint
For service-specific config options or exact parameter order, check in the SDK.
Sources/Services/AWS<Service>/Sources/AWS<Service>/<Service>Client.swift所有服务客户端均遵循相同模式:搭配。
<Service>Client<Service>Client.<Service>ClientConfig模型类型(请求/响应中使用的结构体/枚举)命名空间为:
<Service>ClientTypes- ,
S3ClientTypes.BucketS3ClientTypes.Object DynamoDBClientTypes.AttributeValue- ,
CloudWatchClientTypes.MetricDatumCloudWatchClientTypes.Dimension
swift
import AWSS3
import AWSDynamoDB
// 简单方式 - 自动检测区域
let s3 = try await S3Client()
let dynamo = try await DynamoDBClient()
// 指定区域
let s3 = try S3Client(region: "us-west-2")
// 使用配置 - 参数必须按声明顺序传入
let config = try await S3Client.S3ClientConfig(
useFIPS: true,
awsRetryMode: .adaptive,
maxAttempts: 5,
region: "us-west-2"
)
let client = S3Client(config: config)
// 使用自定义端点和凭证
let config = try await S3Client.S3ClientConfig(
awsCredentialIdentityResolver: resolver,
region: "us-west-2",
endpoint: "https://s3.custom-endpoint.com"
)通用配置参数(必须按声明顺序传入):
-
- 自定义凭证
awsCredentialIdentityResolver -
- 启用FIPS端点
useFIPS -
- 启用双栈端点
useDualStack -
- 重试策略(.adaptive, .standard, .legacy)
awsRetryMode -
- 最大重试次数
maxAttempts -
- AWS区域
region -
- 自定义HTTP客户端(需要HttpClientConfiguration参数):
httpClientEngineswiftimport ClientRuntime let httpConfig = HttpClientConfiguration() let httpClient = URLSessionHTTPClient(httpClientConfiguration: httpConfig) let config = try await S3Client.S3ClientConfig( region: "us-east-1", httpClientEngine: httpClient ) -
- 自定义端点URL
endpoint
如需查看服务特定的配置选项或确切的参数顺序,请查看SDK中的文件。
Sources/Services/AWS<Service>/Sources/AWS<Service>/<Service>Client.swiftCredential Resolvers
凭证解析器
swift
import AWSSDKIdentity
import SmithyIdentity
// Static credentials - pass credential object directly
let creds = AWSCredentialIdentity(accessKey: "AKIA...", secret: "...")
let resolver = StaticAWSCredentialIdentityResolver(creds)
// Assume role - REQUIRES underlying resolver
let underlying = try DefaultAWSCredentialIdentityResolverChain()
let resolver = try STSAssumeRoleAWSCredentialIdentityResolver(
awsCredentialIdentityResolver: underlying,
roleArn: "arn:aws:iam::123456789012:role/MyRole",
sessionName: "session-name"
)
// Use in config
let config = try await S3Client.S3ClientConfig(
awsCredentialIdentityResolver: resolver,
region: "us-west-2"
)swift
import AWSSDKIdentity
import SmithyIdentity
// 静态凭证 - 直接传入凭证对象
let creds = AWSCredentialIdentity(accessKey: "AKIA...", secret: "...")
let resolver = StaticAWSCredentialIdentityResolver(creds)
// 扮演角色 - 需要底层解析器
let underlying = try DefaultAWSCredentialIdentityResolverChain()
let resolver = try STSAssumeRoleAWSCredentialIdentityResolver(
awsCredentialIdentityResolver: underlying,
roleArn: "arn:aws:iam::123456789012:role/MyRole",
sessionName: "session-name"
)
// 在配置中使用
let config = try await S3Client.S3ClientConfig(
awsCredentialIdentityResolver: resolver,
region: "us-west-2"
)Waiters
等待器
Import . WaiterOptions requires parameter:
SmithyWaitersAPImaxWaitTimeswift
import AWSS3
import SmithyWaitersAPI
let client = try await S3Client()
_ = try await client.waitUntilBucketExists(
options: WaiterOptions(maxWaitTime: 120.0),
input: HeadBucketInput(bucket: "my-bucket")
)导入。WaiterOptions需要参数:
SmithyWaitersAPImaxWaitTimeswift
import AWSS3
import SmithyWaitersAPI
let client = try await S3Client()
_ = try await client.waitUntilBucketExists(
options: WaiterOptions(maxWaitTime: 120.0),
input: HeadBucketInput(bucket: "my-bucket")
)Pagination
分页
swift
let input = ListObjectsV2Input(bucket: "my-bucket")
for try await page in client.listObjectsV2Paginated(input: input) {
for object in page.contents ?? [] {
print(object.key ?? "")
}
}swift
let input = ListObjectsV2Input(bucket: "my-bucket")
for try await page in client.listObjectsV2Paginated(input: input) {
for object in page.contents ?? [] {
print(object.key ?? "")
}
}Presigned URLs
预签名URL
swift
let url = try await client.presignedURLForGetObject(
input: GetObjectInput(bucket: "my-bucket", key: "file.pdf"),
expiration: 3600
)swift
let url = try await client.presignedURLForGetObject(
input: GetObjectInput(bucket: "my-bucket", key: "file.pdf"),
expiration: 3600
)Common Operations
常见操作
swift
// Put object
_ = try await client.putObject(input: PutObjectInput(
body: .data(data),
bucket: "bucket",
key: "key"
))
// Get object
let output = try await client.getObject(input: GetObjectInput(bucket: "bucket", key: "key"))
let data = try await output.body?.readData()
// List buckets
let response = try await client.listBuckets(input: ListBucketsInput())
for bucket in response.buckets ?? [] {
print(bucket.name ?? "")
}swift
// 上传对象
_ = try await client.putObject(input: PutObjectInput(
body: .data(data),
bucket: "bucket",
key: "key"
))
// 获取对象
let output = try await client.getObject(input: GetObjectInput(bucket: "bucket", key: "key"))
let data = try await output.body?.readData()
// 列出存储桶
let response = try await client.listBuckets(input: ListBucketsInput())
for bucket in response.buckets ?? [] {
print(bucket.name ?? "")
}