This topic describes how to use the OSS Swift SDK to list all objects in a specified bucket.
Notes
The sample code in this topic uses the China (Hangzhou) region (region ID:
cn-hangzhou) as an example. By default, a public endpoint is used. If you want to access OSS from other Alibaba Cloud services in the same region, you can use an internal endpoint. For more information about the regions and endpoints supported by OSS, see Regions and endpoints.To list objects, you must have the
oss:ListObjectspermission. For more information, see Grant custom permissions to a RAM user.
Sample code
The following code shows how to use the ListObjectsV2 method to list objects in a specified bucket.
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
// 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 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)
// Specify the token from which the list operation starts.
var continueToken: String?
// Check whether all objects are listed.
var isTruncated: Bool = false
repeat {
let result = try await client.listObjectsV2(
ListObjectsV2Request(
bucket: bucket,
maxKeys: 10,
continuationToken: continueToken
)
)
// Traverse the object list in the current page.
for content in result.contents ?? [] {
// Print the object metadata: object name, size in bytes, and last modified time.
print("Object key:\(content.key ?? ""), size: \(String(describing: content.size)), last modified: \(String(describing: content.lastModified))")
}
isTruncated = result.isTruncated ?? false
continueToken = result.nextContinuationToken
} while isTruncated
} catch {
// Print the error.
print("error: \(error)")
}
}
}Common scenarios
References
For the complete sample code used to list objects, see GitHub sample.
For more information about the API operation used to list objects, see ListObjectsV2.