Check whether a file exists (Swift SDK)

Updated at:

Use the OSS Swift SDK to check whether a file (object) exists in a bucket.

Prerequisites

  • The sample code uses the China (Hangzhou) region ID cn-hangzhou and a public endpoint. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about supported regions and endpoints, see Regions and endpoints.

  • You must have the oss:GetObject permission. For more information, see Grant custom permissions to a RAM user.

Sample code

The following code checks whether a file exists.

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"
            // Specify the bucket name.
            let bucket = "yourBucketName"
            // Optional. Specify the domain name used to access OSS. For example, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com for China (Hangzhou).
            let endpoint: String? = nil
            // Specify the name of the object (file) to check.
            let key = "yourObjectName"

            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
            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 whether the object exists.
            let result = try await client.isObjectExist(bucket, key)
            print("result:\n\(result)") // Print the check result.

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

References