Tous les produits
Search
Centre de documentation

Object Storage Service:List objects (Swift SDK)

Dernière mise à jour :Aug 18, 2026

Cette rubrique explique comment utiliser le SDK Swift pour OSS afin de répertorier tous les objets d'un bucket spécifié.

Notes

  • Les exemples de code de cette rubrique utilisent la région Chine (Hangzhou) (ID de région : cn-hangzhou) à titre d'exemple. Par défaut, un endpoint public est utilisé. Pour accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints pris en charge par OSS, consultez Régions et endpoints.

  • Pour lister des objets, vous devez disposer de l'autorisation oss:ListObjects. Pour plus d'informations, consultez Accorder des autorisations personnalisées à un utilisateur RAM.

Exemple de code

Le code suivant montre comment utiliser la méthode ListObjectsV2 pour lister les objets d'un bucket spécifié.

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)")
        }
    }
}

Scénarios courants

Utiliser un paginateur pour lister les objets d'un bucket spécifié

Le code suivant montre comment utiliser la méthode ListObjectsV2 avec un paginateur pour lister les objets d'un bucket spécifié.

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)
            // Create a paginator request object to traverse all objects in the bucket with paging.
            let paginator = client.listObjectsV2Paginator(
                ListObjectsV2Request(
                    bucket: bucket // Specify the name of the bucket whose objects you want to list.
                )
            )
            // Traverse the paginated results to obtain object information page by page.
            for try await page in paginator {
                // Traverse the object list in the current page.
                for content in page.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))")
                }
            }
        } catch {
            // Print the error.
            print("error: \(error)")
        }
    }
}

Références

  • Pour obtenir l'exemple de code complet permettant de lister des objets, consultez l'exemple GitHub.

  • Pour plus d'informations sur l'opération API utilisée pour lister des objets, consultez ListObjectsV2.