Simple download (Swift SDK)
Download an object from a bucket by using the OSS Swift SDK.
Notes
-
The sample code in this topic uses the China (Hangzhou) region (Region ID:
cn-hangzhou) and a public endpoint. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information, see Regions and Endpoints.
Permissions
By default, an Alibaba Cloud account has full permissions. RAM users or RAM roles under an Alibaba Cloud account do not have any permissions by default. The Alibaba Cloud account or account administrator must grant operation permissions through RAM policies or Bucket Policy.
|
API |
Action |
Description |
|
GetObject |
|
Downloads an object. |
|
|
When downloading an object, if you specify the object version through versionId, this permission is required. |
|
|
|
When downloading an object, if the object metadata contains X-Oss-Server-Side-Encryption: KMS, this permission is required. |
Sample code
The following code downloads an object from a bucket to memory.
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
do {
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to cn-hangzhou.
let region = "cn-hangzhou"
// Specify the bucket name.
let bucket = "yourBucketName"
// Optional. Specify the domain name used to access OSS. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
let endpoint: String? = nil
// Specify the name of the object to download.
let key = "yourObjectName"
// Obtain access credentials from environment variables. Before running this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
let credentialsProvider = EnvironmentCredentialsProvider()
// Configure OSS client parameters.
let config = Configuration.default()
.withRegion(region) // Set the region.
.withCredentialsProvider(credentialsProvider) // Set the credentials.
// Set the Endpoint.
if let endpoint = endpoint {
config.withEndpoint(endpoint)
}
// Create an OSS client instance.
let client = Client(config)
// Download the object.
let result = try await client.getObject(
GetObjectRequest(
bucket: bucket,
key: key
)
)
print("result:\n\(result)")
} catch {
// Stop the program and print the error message.
print("error: \(error)")
}
}
}
Scenarios
References
-
For the complete sample code for downloading an object to a local file, see GitHub example.
-
For more information about the API operation for downloading objects, see GetObject.