List all objects, a specified number of objects, or objects with a specific prefix in a versioned bucket by using OSS SDK for Swift.
Notes
-
The sample code uses the region ID
cn-hangzhoufor the China (Hangzhou) region. By default, a public endpoint is used. 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 list objects, you must have the
oss:ListObjectVersionspermission. For more information, see Attach a custom policy to a RAM user.
Sample code
The following sample code lists all object versions, including delete markers, in a bucket:
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
do {
// Specify the region of the bucket. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou.
let region = "cn-hangzhou"
// Specify the bucket name.
let bucket = "yourBucketName"
// Optional. Specify the domain name to access OSS. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
let endpoint: String? = nil
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
let credentialsProvider = EnvironmentCredentialsProvider()
// Configure parameters for the OSS client.
let config = Configuration.default()
.withRegion(region) // Set the region of the bucket.
.withCredentialsProvider(credentialsProvider) // Set the access credential.
// Set the endpoint.
if let endpoint = endpoint {
config.withEndpoint(endpoint)
}
// Create an OSS client instance.
let client = Client(config)
// List the versions of all objects in the specified bucket.
var isTruncated = false
var keyMarker: String?
var versionIdMarker: String?
repeat {
let result = try await client.listObjectVersions(
ListObjectVersionsRequest(
bucket: bucket,
keyMarker: keyMarker,
versionIdMarker: versionIdMarker
)
)
for version in result.versions ?? [] {
print("key: \(version.key ?? ""), version id: \(version.versionId ?? "")")
}
isTruncated = result.isTruncated ?? false
keyMarker = result.nextKeyMarker
versionIdMarker = result.nextVersionIdMarker
} while isTruncated
} catch {
// Error output.
print("Error: \(error)")
}
}
}
References
-
For the complete sample code for listing object versions, see GitHub example.