Delete files (Swift SDK)

Updated at:

This topic describes how to use the OSS Swift software development kit (SDK) to delete a single file or multiple files.

Warning

Use the delete operation with caution. Deleted files cannot be recovered.

Notes

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

  • To delete files, you must have the oss:DeleteObject permission. For more information, see Grant a custom access policy to a RAM user.

Sample code

Delete a single file

import AlibabaCloudOSS
import Foundation

@main
struct Main {
    static func main() async {
        do {
            // The region where the bucket is located. Example: cn-hangzhou for China (Hangzhou).
            let region = "cn-hangzhou"
            // The bucket name.
            let bucket = "yourBucketName"
            // Optional. The domain name to access OSS. For China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
            let endpoint: String? = nil
            // The name of the object to delete, such as test.txt.
            let key = "yourObjectName"

            // Initialize the credential provider to load credentials from environment variables.
            let credentialsProvider = EnvironmentCredentialsProvider()

            // Configure the OSS client.
            let config = Configuration.default()
                .withRegion(region)
                .withCredentialsProvider(credentialsProvider)
                
            // Set the endpoint.
            if let endpoint = endpoint {
                config.withEndpoint(endpoint)
            }

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

            // Send a request to delete the object.
            let result = try await client.deleteObject(
                DeleteObjectRequest(
                    bucket: bucket,
                    key: key
                )
            )
            print("result:\n\(result)")

        } catch {
            // Print the error message and continue.
            print("error: \(error)")
        }
    }
}

Delete multiple specified files

import AlibabaCloudOSS
import Foundation

@main
struct Main {
    static func main() async {
        do {
            // The region where the bucket is located. Example: cn-hangzhou for China (Hangzhou).
            let region = "cn-hangzhou"
            // The bucket name.
            let bucket = "yourBucketName"
            // Optional. The domain name to access OSS. For China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
            let endpoint: String? = nil
            // The names of the objects to delete, separated by commas, such as object1.txt,object2.jpg.
            let objects = "yourObjectName1,yourObjectName2"

            // Initialize the credential provider to load OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET from environment variables.
            let credentialsProvider = EnvironmentCredentialsProvider()

            // Configure the OSS client.
            let config = Configuration.default()
                .withRegion(region)        // Set the region where the bucket is located.
                .withCredentialsProvider(credentialsProvider)  // Set the access credentials.
                
            // Set the endpoint.
            if let endpoint = endpoint {
                config.withEndpoint(endpoint)
            }

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

            // Parse the object name string into a DeleteObject array.
            var deleteObjects: [DeleteObject] = []
            for object in objects.components(separatedBy: ",") {
                deleteObjects.append(DeleteObject(key: object))
            }

            // Perform a batch delete operation.
            let result = try await client.deleteMultipleObjects(
                DeleteMultipleObjectsRequest(
                    bucket: bucket,
                    delete: Delete(objects: deleteObjects)
                )
            )
            print("result:\n\(result)")

        } catch {
            // Print the error message and continue.
            print("error: \(error)")
        }
    }
}

FAQ

How can I confirm that a file is deleted after I use the Swift SDK to delete it?

When you use the OSSClient deleteObject method in the OSS Swift SDK to delete a single file, the operation is successful if no exception is thrown. To verify that the file is deleted, you can call the OSSClient doesObjectExist method. This method checks whether the specified file exists. If this method returns false, the file is deleted. For more information, see Determine whether a file exists (Swift SDK).

References

  • For complete sample code for deleting a single file, see the GitHub example delete_object.

  • For information about the API operation for deleting a single file, see DeleteObject.

  • For information about the API operation for deleting multiple files, see DeleteMultipleObjects.