Use isBucketExist to check whether a bucket exists and is accessible with your current credentials.
Prerequisites
Before you begin, ensure that you have:
The
oss:GetBucketAclpermission on the target bucketThe
OSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETenvironment variables set with valid AccessKey credentials
Usage notes
The sample code uses the China (Hangzhou) region (
cn-hangzhou) and a public endpoint by default. To access OSS from other Alibaba Cloud services in the same region over the internal network, use an internal endpoint. For supported regions and endpoints, see Regions and endpoints.
Check whether a bucket exists
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
do {
// --- Client initialization ---
// Specify the region where the bucket is located.
let region = "cn-hangzhou"
// Optional. Specify the endpoint. Defaults to the public endpoint for the region.
let endpoint: String? = nil
// Load credentials from environment variables.
// Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this code.
let credentialsProvider = EnvironmentCredentialsProvider()
let config = Configuration.default()
.withRegion(region)
.withCredentialsProvider(credentialsProvider)
if let endpoint = endpoint {
config.withEndpoint(endpoint)
}
let client = Client(config)
// --- Core operation ---
// Specify the bucket name.
let bucket = "yourBucketName"
let result = try await client.isBucketExist(bucket)
print("result:\n\(result)")
} catch {
print("error: \(error)")
}
}
}Replace yourBucketName with the name of the bucket you want to check.
References
For the complete sample, see isBucketExist on GitHub.
To grant RAM users the required permission, see Grant custom permissions to a RAM user.