aws-sdk-swift-usage

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AWS SDK for Swift

AWS SDK for Swift

Async Code Structure

异步代码结构

All SDK operations are async. Use
@main
entry point:
swift
@main
struct Main {
    static func main() async throws {
        let client = try await S3Client()
        // ... async operations
    }
}
所有SDK操作均为异步。使用
@main
作为入口点:
swift
@main
struct Main {
    static func main() async throws {
        let client = try await S3Client()
        // ... async operations
    }
}

CRITICAL: Use Struct Config Types

重要提示:使用结构体类型的配置

NEVER use
S3ClientConfiguration
or
DynamoDBClientConfiguration
- these are DEPRECATED classes.
ALWAYS use the struct-based config types:
  • S3Client.S3ClientConfig
    (not S3ClientConfiguration)
  • DynamoDBClient.DynamoDBClientConfig
    (not DynamoDBClientConfiguration)
  • STSClient.STSClientConfig
    (not STSClientConfiguration)
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")
切勿使用
S3ClientConfiguration
DynamoDBClientConfiguration
——这些是已废弃的类。
请始终使用基于结构体的配置类型:
  • S3Client.S3ClientConfig
    (而非S3ClientConfiguration)
  • DynamoDBClient.DynamoDBClientConfig
    (而非DynamoDBClientConfiguration)
  • STSClient.STSClientConfig
    (而非STSClientConfiguration)
配置参数必须按照声明顺序传入。创建配置时,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:
<Service>Client
with
<Service>Client.<Service>ClientConfig
.
Model types (structs/enums used in requests/responses) are namespaced under
<Service>ClientTypes
:
  • S3ClientTypes.Bucket
    ,
    S3ClientTypes.Object
  • DynamoDBClientTypes.AttributeValue
  • CloudWatchClientTypes.MetricDatum
    ,
    CloudWatchClientTypes.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):
  • awsCredentialIdentityResolver
    - Custom credentials
  • useFIPS
    - Enable FIPS endpoints
  • useDualStack
    - Enable dual-stack endpoints
  • awsRetryMode
    - Retry strategy (.adaptive, .standard, .legacy)
  • maxAttempts
    - Max retry attempts
  • region
    - AWS region
  • httpClientEngine
    - Custom HTTP client (requires HttpClientConfiguration parameter):
    swift
    import ClientRuntime
    let httpConfig = HttpClientConfiguration()
    let httpClient = URLSessionHTTPClient(httpClientConfiguration: httpConfig)
    let config = try await S3Client.S3ClientConfig(
        region: "us-east-1",
        httpClientEngine: httpClient
    )
  • endpoint
    - Custom endpoint URL
For service-specific config options or exact parameter order, check
Sources/Services/AWS<Service>/Sources/AWS<Service>/<Service>Client.swift
in the SDK.
所有服务客户端均遵循相同模式:
<Service>Client
搭配
<Service>Client.<Service>ClientConfig
模型类型(请求/响应中使用的结构体/枚举)命名空间为
<Service>ClientTypes
  • S3ClientTypes.Bucket
    ,
    S3ClientTypes.Object
  • DynamoDBClientTypes.AttributeValue
  • CloudWatchClientTypes.MetricDatum
    ,
    CloudWatchClientTypes.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
    - 自定义凭证
  • useFIPS
    - 启用FIPS端点
  • useDualStack
    - 启用双栈端点
  • awsRetryMode
    - 重试策略(.adaptive, .standard, .legacy)
  • maxAttempts
    - 最大重试次数
  • region
    - AWS区域
  • httpClientEngine
    - 自定义HTTP客户端(需要HttpClientConfiguration参数):
    swift
    import ClientRuntime
    let httpConfig = HttpClientConfiguration()
    let httpClient = URLSessionHTTPClient(httpClientConfiguration: httpConfig)
    let config = try await S3Client.S3ClientConfig(
        region: "us-east-1",
        httpClientEngine: httpClient
    )
  • endpoint
    - 自定义端点URL
如需查看服务特定的配置选项或确切的参数顺序,请查看SDK中的
Sources/Services/AWS<Service>/Sources/AWS<Service>/<Service>Client.swift
文件。

Credential 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
SmithyWaitersAPI
. WaiterOptions requires
maxWaitTime
parameter:
swift
import AWSS3
import SmithyWaitersAPI

let client = try await S3Client()
_ = try await client.waitUntilBucketExists(
    options: WaiterOptions(maxWaitTime: 120.0),
    input: HeadBucketInput(bucket: "my-bucket")
)
导入
SmithyWaitersAPI
。WaiterOptions需要
maxWaitTime
参数:
swift
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 ?? "")
}