Este tema describe cómo usar el OSS Swift SDK para listar todos los objetos de un bucket específico.
Notas
El código de ejemplo de este tema usa la región China (Hangzhou) (ID de región:
cn-hangzhou) como referencia. De forma predeterminada, se usa un endpoint público. Si necesita acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, use un endpoint interno. Para obtener más información sobre las regiones y los endpoints compatibles con OSS, consulte Regions and endpoints.Para listar objetos, debe contar con el permiso
oss:ListObjects. Para obtener más información, consulte Grant custom permissions to a RAM user.
Código de ejemplo
A continuación se muestra cómo usar el método ListObjectsV2 para listar los objetos de un bucket específico.
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)")
}
}
}
Escenarios comunes
Usar un paginador para listar los objetos de un bucket específico
Referencias
Para consultar el código de ejemplo completo que se usa para listar objetos, vea el ejemplo en GitHub.
Para obtener más información sobre la operación de API que se usa para listar objetos, consulte ListObjectsV2.