Restore objects (Swift SDK)

更新时间:
复制 MD 格式

In a versioning-enabled bucket, different versions of an object can have different storage classes. The Restorebject operation restores the current version of an object by default. You can specify a version ID to restore a specific version.

Considerations

  • This topic uses the China (Hangzhou) region ID cn-hangzhou as an example. The default endpoint is a public endpoint. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about region-to-endpoint mappings, see OSS regions and endpoints.

  • To restore an object, you must have the oss:RestoreObject permission. For more information, see Grant custom permissions to a RAM user.

Sample code

The following sample code shows how to restore an Archive, Cold Archive, or Deep Cold Archive object:

import AlibabaCloudOSS
import Foundation

@main
struct Main {
    static func main() async {
        do {
            // Specify the region where the bucket is located. Example: cn-hangzhou for China (Hangzhou)
            let region = "cn-hangzhou"
            // Specify the bucket name
            let bucket = "yourBucketName"
            // Optional. Specify the endpoint for accessing OSS. For China (Hangzhou), the endpoint is https://oss-cn-hangzhou.aliyuncs.com
            let endpoint: String? = nil
            // Specify the name of the object to restore (e.g., test.txt)
            let key = "yourObjectName"
            // Version ID
            let versionId = "versionId"

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

            // Configure OSS client parameters
            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)

            // Execute the restore object operation
            let result = try await client.restoreObject(
                RestoreObjectRequest(
                    bucket: bucket,
                    key: key,
                    versionId: versionId
                )
            )
            print("result:\n\(result)")

        } catch {
            // Output error message and continue execution
            print("error: \(error)")
        }
    }
}

References

  • For complete sample code for restoring objects, see GitHub.

  • For more information about the API operation for restoring objects, see RestoreObject.

  • For more information about how to restore objects, see Restore objects.