Este tópico descreve como usar o OSS Swift SDK para listar todos os objetos em um bucket especificado.
Observações
O código de exemplo neste tópico usa a região China (Hangzhou) (ID da região:
cn-hangzhou) como exemplo. Por padrão, o sistema utiliza um endpoint público. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre as regiões e os endpoints compatíveis com o OSS, consulte Regiões e endpoints.Para listar objetos, você precisa da permissão
oss:ListObjects. Para obter mais informações, consulte Conceder permissões personalizadas a um usuário RAM.
Código de exemplo
O código a seguir mostra como usar o método ListObjectsV2 para listar objetos em um 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)")
}
}
}
Cenários comuns
Usar um paginador para listar objetos em um bucket especificado
Referências
Para obter o código de exemplo completo usado para listar objetos, consulte o exemplo no GitHub.
Para obter mais informações sobre a operação de API usada para listar objetos, consulte ListObjectsV2.