List buckets (Swift SDK)

Updated at:

A bucket is a container that stores objects. All objects must be stored in a bucket. When you list buckets, they are arranged in alphabetical order. You can list buckets that meet specific criteria across all regions under your account.

Notes

  • The sample code in this topic uses the China (Hangzhou) region (ID: cn-hangzhou) as an example. The public endpoint is used by default. To access OSS from other Alibaba Cloud products in the same region, you can use the internal network endpoint. For more information about the mappings between OSS regions and endpoints, see Regions and endpoints.

  • To list buckets, you must have the oss:ListBuckets permission. For more information, see Grant custom access policies to a RAM user.

List all buckets

The following code shows how to list all buckets across all regions under your account.

import AlibabaCloudOSS
import Foundation

@main
struct Main {
    static func main() async {
        do {
            // Specify the region where the bucket is located. For example, set the region to cn-hangzhou for China (Hangzhou).
            let region = "cn-hangzhou"
            // Optional. Specify the domain name to access OSS. For example, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com for China (Hangzhou).
            let endpoint: String? = nil

            // Load credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET in advance.
            let credentialsProvider = EnvironmentCredentialsProvider()

            // Configure the 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)

            // Create a paginator to traverse buckets.
            let paginator = client.listBucketsPaginator(ListBucketsRequest())

            // Traverse all buckets and print their information.
            for try await page in paginator {
                for bucket in page.buckets ?? [] {
                    print("Bucket name: \(bucket.name ?? ""), Storage class: \(bucket.storageClass ?? ""), Region: \(bucket.location ?? "")")
                }
            }

        } catch {
            // Catch and handle exceptions.
            print("error:\n\(error)")
        }
    }
}

References