Initialize an OSS Client instance and modify the default configurations to send requests to Object Storage Service (OSS) by using Swift SDK V2.
Notes
-
Before you initialize the OSS Client, configure your access credentials. The examples in this topic read access credentials from environment variables. For more configuration examples, see Configure access credentials (Swift SDK).
-
For information about the regions and endpoints that OSS supports, see Regions and Endpoints.
Prerequisites
Before you configure a client using the following code samples, you must configure environment variables to store the AccessKey pair of a RAM user.
-
-
Configure environment variables for the AccessKey pair.
Linux
-
Run the following commands on the CLI to add the configurations of the environment variables to the
~/.bashrcfile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc-
Apply the changes.
source ~/.bashrc -
Check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
Run the following command in the terminal to view the default shell type:
echo $SHELL-
Configure environment variables based on the default shell type.
Zsh
-
Run the following commands to add the configurations of the environment variables to the
~/.zshrcfile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Apply the changes.
source ~/.zshrc -
Check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Run the following commands to add the configurations of the environment variables to the
~/.bash_profilefile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Apply the changes.
source ~/.bash_profile -
Check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
Run the following commands in CMD:
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"-
Check whether the environment variables take effect:
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
Run the following commands in PowerShell:
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)-
Check whether the environment variable takes effect:
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
-
-
After you set the environment variables, you must restart any open terminal sessions or IDEs for the changes to take effect.
Default configuration example
-
Swift SDK V2 uses V4 signatures by default. When you initialize the Client, you must specify an Alibaba Cloud region ID to identify the region to which the request is sent. This example uses the China (Hangzhou) region ID: cn-hangzhou. For more information about region IDs, see Regions and Endpoints.
-
Swift SDK V2 lets you use the Endpoint parameter to customize the endpoint for service requests. If you do not specify an endpoint, the SDK constructs a public network access endpoint based on the region information. For example, if the region is 'cn-hangzhou', the constructed endpoint is 'https://oss-cn-hangzhou.aliyuncs.com'.
-
When Swift SDK V2 constructs an endpoint, it uses the HTTPS protocol by default. To use the HTTP protocol, specify the protocol as part of the endpoint, for example, 'http://oss-cn-hangzhou.aliyuncs.com'.
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
// Specify the region where the bucket is located. Example: China (Hangzhou) is cn-hangzhou.
let region = "cn-hangzhou"
// Optional. Specify the endpoint to access OSS. For China (Hangzhou), set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
let endpoint: String? = nil
// Obtain access credentials from environment variables. Before you run this 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 where the bucket is located.
.withCredentialsProvider(credentialsProvider) // Set the access credentials.
// Set a custom endpoint.
if let endpoint = endpoint {
config.withEndpoint(endpoint)
}
// Create an OSS client instance.
let client = Client(config)
}
}
Configuration examples for common scenarios
Internal endpoint configuration example
If your application runs on an Alibaba Cloud Elastic Compute Service (ECS) instance and frequently accesses OSS resources in the same region, use an internal endpoint to reduce traffic costs and improve access speed.
The following example shows how to configure an OSSClient with an OSS internal endpoint.
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
// Specify the region where the bucket is located. Example: China (Hangzhou) is cn-hangzhou.
let region = "cn-hangzhou"
let endpoint: String? = "https://oss-cn-hangzhou-internal.aliyuncs.com" // Optional. Specify the internal endpoint to access OSS. For China (Hangzhou), set the Endpoint to https://oss-cn-hangzhou-internal.aliyuncs.com.
// Obtain access credentials from environment variables. Before you run this 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 where the bucket is located.
.withCredentialsProvider(credentialsProvider) // Set the access credentials.
// You can also configure an internal endpoint by setting useInternalEndpoint = true without specifying an internal endpoint.
// .withUseInternalEndpoint(true)
// Set a custom endpoint.
if let endpoint = endpoint {
config.withEndpoint(endpoint)
}
// Create an OSS client instance.
let client = Client(config)
}
}
Custom domain name configuration example
If you have multiple OSS buckets for different purposes, set different subdomains for each bucket to better manage and organize your resources.
The following example shows how to configure an OSSClient with a custom domain name.
You must first map the custom domain name to the default domain name of the bucket. Otherwise, an error will occur. For more information, see Access OSS using a custom domain name.
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
// Specify the region where the bucket is located. Example: China (Hangzhou) is cn-hangzhou.
let region = "cn-hangzhou"
let endpoint: String? = "https://www.example-***.com" // Required. Specify your custom domain name. For example, www.example-***.com.
// Obtain access credentials from environment variables. Before you run this 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 where the bucket is located.
.withCredentialsProvider(credentialsProvider) // Set the access credentials.
.withUseCname(true) // Note that you must set this parameter to true to enable the CNAME option. Otherwise, you cannot use a custom domain name.
// Set a custom endpoint.
if let endpoint = endpoint {
config.withEndpoint(endpoint)
}
// Create an OSS client instance.
let client = Client(config)
}
}
Transfer acceleration endpoint configuration example
The following example shows how to configure an OSSClient with a transfer acceleration endpoint.
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
// Specify the region where the bucket is located. Example: China (Hangzhou) is cn-hangzhou.
let region = "cn-hangzhou"
let endpoint: String? = "https://oss-accelerate.aliyuncs.com" // Optional. Specify the transfer acceleration endpoint for the bucket's region. For China (Hangzhou), set the Endpoint to 'https://oss-accelerate.aliyuncs.com'.
// Obtain access credentials from environment variables. Before you run this 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 where the bucket is located.
.withCredentialsProvider(credentialsProvider) // Set the access credentials.
// You can also configure a transfer acceleration endpoint by setting useAccelerateEndpoint = true without specifying a transfer acceleration endpoint.
// .withUseAccelerateEndpoint(true)
// Set a custom endpoint.
if let endpoint = endpoint {
config.withEndpoint(endpoint)
}
// Create an OSS client instance.
let client = Client(config)
}
}
Private domain configuration example
The following example shows how to configure an OSSClient with a private domain.
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
// Specify the region where the bucket is located. Example: China (Hangzhou) is cn-hangzhou.
let region = "cn-hangzhou"
let endpoint: String? = "https://service.corp.example.com" // Required. Specify your private domain. For example, https://service.corp.example.com.
// Obtain access credentials from environment variables. Before you run this 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 where the bucket is located.
.withCredentialsProvider(credentialsProvider) // Set the access credentials.
// Set a custom endpoint.
if let endpoint = endpoint {
config.withEndpoint(endpoint)
}
// Create an OSS client instance.
let client = Client(config)
}
}
Alibaba Finance Cloud configuration example
The following example shows how to configure an OSSClient with an Alibaba Finance Cloud domain name.
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
// Specify the region where the bucket is located. For China (Hangzhou) Finance, set the Region to cn-hangzhou-finance.
let region = "cn-hangzhou-finance"
let endpoint: String? = "https://oss-cn-hzjbp-a-internal.aliyuncs.com" // Required. Specify the internal endpoint for the bucket's region. For China (Hangzhou) Finance, set the Endpoint to 'https://oss-cn-hzjbp-a-internal.aliyuncs.com'.
// Obtain access credentials from environment variables. Before you run this 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 where the bucket is located.
.withCredentialsProvider(credentialsProvider) // Set the access credentials.
// Set a custom endpoint.
if let endpoint = endpoint {
config.withEndpoint(endpoint)
}
// Create an OSS client instance.
let client = Client(config)
}
}
Alibaba Gov Cloud configuration example
The following example shows how to configure an OSSClient with an Government cloud domain name.
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
// Specify the region where the bucket is located. For China North 2 Alibaba Gov 1, set the Region to cn-north-2-gov-1.
let region = "cn-north-2-gov-1"
// Required. Specify the internal endpoint for the bucket's region. For China North 2 Alibaba Gov 1, set the Endpoint to 'https://oss-cn-north-2-gov-1-internal.aliyuncs.com'.
let endpoint: String? = "https://oss-cn-north-2-gov-1-internal.aliyuncs.com"
// Obtain access credentials from environment variables. Before you run this 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 where the bucket is located.
.withCredentialsProvider(credentialsProvider) // Set the access credentials.
// Set a custom endpoint.
if let endpoint = endpoint {
config.withEndpoint(endpoint)
}
// Create an OSS client instance.
let client = Client(config)
}
}
Summary of OSSClient configuration parameters
|
Parameter |
Description |
Example |
|
|
(Required) The region where the request is sent. |
Configuration.region = "cn-hangzhou" |
|
|
The endpoint. |
Configuration.endpoint = "oss-cn-hangzhou.aliyuncs.com" |
|
|
The maximum number of retries for a failed request. |
Configuration.retryMaxAttempts = 5 |
|
|
The retry implementation for HTTP requests. |
Configuration.retryer = customRetryer |
|
|
The interface for logging. |
Configuration.HttpTransport = customLogger |
|
|
(Required) The access credentials. |
Configuration.credentialsProvider = EnvironmentCredentialsProvider() |
|
|
Specifies whether to use the path-style request format (second-level domain). Default: bucket-hosted domain format. |
Configuration.usePathStyle = true |
|
|
Specifies whether to use a custom domain name for access. Default: false. |
Configuration.useCName = true |
|
|
The request timeout interval, in seconds. Default: 15. |
Configuration.timeoutIntervalForRequest = 30 |
|
|
The maximum time allowed for a resource request. Default: 24 hours. |
Configuration.timeoutIntervalForResource = 60 * 60 |
|
|
Specifies whether to skip SSL certificate verification. By default, SSL certificate verification is performed. |
Configuration.enableTLSVerify = true |
|
|
Specifies whether to enable HTTP redirection. Default: false. |
Configuration.enableFollowRedirect = true |
|
|
The maximum number of connections per host. |
Configuration.maxConnectionsPerHost = 5 |
|
|
The signature version. Default: v4. |
Configuration.signerVersion = "v4" |
|
|
The HTTP protocol. Default: HTTPS. |
Configuration.httpProtocol = .https |
|
|
Specifies whether to use a dual-stack endpoint for access. Default: false. |
Configuration.useDualStackEndpoint = true |
|
|
Specifies whether to use a transfer acceleration endpoint for access. Default: false. |
Configuration.useAccelerateEndpoint = true |
|
|
Specifies whether to use an internal endpoint for access. Default: false. |
Configuration.useInternalEndpoint = true |
|
|
Specifies whether to enable CRC-64 validation for uploads. Default: true. |
Configuration.enableUploadCRC64Validation = true |
|
|
Specifies whether to enable CRC-64 validation for downloads. Default: true. |
Configuration.enableDownloadCRC64Validation = true |
|
|
Specifies additional request headers to sign. This is valid only for V4 signatures. |
Configuration.additionalHeaders = ["x-oss-meta-*"] |
|
|
Specifies additional User-Agent information. |
Configuration.userAgent = "MyApp/1.0" |

