Configure a client (Swift SDK)

更新时间:
复制 MD 格式

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

Important

Before you configure a client using the following code samples, you must configure environment variables to store the AccessKey pair of a RAM user.

  1. Create an AccessKey pair for a Resource Access Management (RAM) user that has full OSS access permissions.

    Create an AccessKey pair by using ROS

    You can quickly create an AccessKey pair for a RAM user that has full OSS access permissions by using a Resource Orchestration Service (ROS) script. To do so, go to the wizard for template-based stack creation, select I confirm that Alibaba Cloud ROS may create RAM resources in the Security Confirmation section, and click Create.

    1.png

    After the AccessKey pair is created, copy the AccessKey pair on the Outputs tab.

    image

  2. Configure environment variables for the AccessKey pair.

    Linux

    1. Run the following commands on the CLI to add the configurations of the environment variables to the ~/.bashrc file:

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
      1. Apply the changes.

        source ~/.bashrc
      2. Check whether the environment variables have taken effect:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Run the following command in the terminal to view the default shell type:

      echo $SHELL
      1. Configure environment variables based on the default shell type.

        Zsh

        1. Run the following commands to add the configurations of the environment variables to the ~/.zshrc file:

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
        2. Apply the changes.

          source ~/.zshrc
        3. Check whether the environment variables have taken effect:

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

        Bash

        1. Run the following commands to add the configurations of the environment variables to the ~/.bash_profile file:

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
        2. Apply the changes.

          source ~/.bash_profile
        3. Check whether the environment variables have taken effect:

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Run the following commands in CMD:

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
      1. Check whether the environment variables take effect:

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. 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)
      1. Check whether the environment variable takes effect:

        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  3. After you set the environment variables, you must restart any open terminal sessions or IDEs for the changes to take effect.

Default configuration example

Important
  • 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.

Warning

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

region

(Required) The region where the request is sent.

Configuration.region = "cn-hangzhou"

endpoint

The endpoint.

Configuration.endpoint = "oss-cn-hangzhou.aliyuncs.com"

retryMaxAttempts

The maximum number of retries for a failed request.

Configuration.retryMaxAttempts = 5

retryer

The retry implementation for HTTP requests.

Configuration.retryer = customRetryer

logger

The interface for logging.

Configuration.HttpTransport = customLogger

credentialsProvider

(Required) The access credentials.

Configuration.credentialsProvider = EnvironmentCredentialsProvider()

usePathStyle

Specifies whether to use the path-style request format (second-level domain). Default: bucket-hosted domain format.

Configuration.usePathStyle = true

useCName

Specifies whether to use a custom domain name for access. Default: false.

Configuration.useCName = true

timeoutIntervalForRequest

The request timeout interval, in seconds. Default: 15.

Configuration.timeoutIntervalForRequest = 30

timeoutIntervalForResource

The maximum time allowed for a resource request. Default: 24 hours.

Configuration.timeoutIntervalForResource = 60 * 60

enableTLSVerify

Specifies whether to skip SSL certificate verification. By default, SSL certificate verification is performed.

Configuration.enableTLSVerify = true

enableFollowRedirect

Specifies whether to enable HTTP redirection. Default: false.

Configuration.enableFollowRedirect = true

maxConnectionsPerHost

The maximum number of connections per host.

Configuration.maxConnectionsPerHost = 5

signerVersion

The signature version. Default: v4.

Configuration.signerVersion = "v4"

httpProtocol

The HTTP protocol. Default: HTTPS.

Configuration.httpProtocol = .https

useDualStackEndpoint

Specifies whether to use a dual-stack endpoint for access. Default: false.

Configuration.useDualStackEndpoint = true

useAccelerateEndpoint

Specifies whether to use a transfer acceleration endpoint for access. Default: false.

Configuration.useAccelerateEndpoint = true

useInternalEndpoint

Specifies whether to use an internal endpoint for access. Default: false.

Configuration.useInternalEndpoint = true

enableUploadCRC64Validation

Specifies whether to enable CRC-64 validation for uploads. Default: true.

Configuration.enableUploadCRC64Validation = true

enableDownloadCRC64Validation

Specifies whether to enable CRC-64 validation for downloads. Default: true.

Configuration.enableDownloadCRC64Validation = true

additionalHeaders

Specifies additional request headers to sign. This is valid only for V4 signatures.

Configuration.additionalHeaders = ["x-oss-meta-*"]

userAgent

Specifies additional User-Agent information.

Configuration.userAgent = "MyApp/1.0"

FAQ

How can I improve transfer speed when accessing OSS from other Alibaba Cloud products in the same region?

Access OSS from other Alibaba Cloud products, such as ECS instances, in the same region and use an internal endpoint. For more information, see Access OSS resources from ECS instances over an internal network.

How do I view the AccessKey information of a RAM user?

  1. To view the AccessKey of a RAM user, log on to the RAM console and select the user to view the AccessKey information.

  2. The AccessKey secret for a RAM user is displayed only at creation and cannot be retrieved afterward. If you forget the secret, go to the RAM console, select the user, and create a new AccessKey. For more information, see Create an AccessKey.

If an error occurs, how do I find the specific error type?

For error types, see the OSS Error codes documentation. For common authentication errors, see 02-AUTH.