Check whether a bucket exists (Swift SDK)

Updated at:

This topic describes how to check whether a specified bucket exists.

Notes

  • The sample code in this topic uses the China (Hangzhou) region (cn-hangzhou) and a public endpoint by default. If you want to access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about the regions and endpoints that OSS supports, see Regions and endpoints.

  • To check whether a bucket exists, you must have the oss:GetBucketAcl permission. For more information, see Grant custom permissions to a RAM user.

Sample code

You can use the following code to check whether a bucket exists.

import AlibabaCloudOSS
import Foundation

@main
struct Main {
    static func main() async {
        do {
            // Specify the region where the bucket is located. This example uses cn-hangzhou for the China (Hangzhou) region.
            let region = "cn-hangzhou"
            // Specify the bucket name.
            let bucket = "yourBucketName"
            // Optional. Specify the endpoint to access OSS. This example uses https://oss-cn-hangzhou.aliyuncs.com for the China (Hangzhou) region.
            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.
                .withCredentialsProvider(credentialsProvider) // Set the credentials.
                
            // Set the endpoint.
            if let endpoint = endpoint {
                config.withEndpoint(endpoint)
            }

            // Create an OSS client instance.
            let client = Client(config)

            // Check if the bucket exists.
            let result = try await client.isBucketExist(bucket)
            print("result:\n\(result)") // Print the result.

        } catch {
            // Stop the program and print the error.
            print("error: \(error)")
        }
    }
}

References