Use the OSS Swift SDK to list objects in a bucket with ListObjectsV2. The SDK supports two approaches: manual pagination with a continuation token, and a built-in paginator that handles token management automatically.
Prerequisites
Before you begin, ensure that you have:
The
oss:ListObjectspermission. For details, see Grant custom permissions to a RAM user.The
OSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETenvironment variables configured with your access credentials.
Usage notes
The sample code uses the China (Hangzhou) region (
cn-hangzhou) and a public endpoint by default. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint instead. For supported regions and endpoints, see Regions and endpoints.
Choose a listing method
Both methods call the same ListObjectsV2 API and return the same data. The difference is in how pagination is handled.
| Method | How pagination works | When to use |
|---|---|---|
| Manual pagination | Track nextContinuationToken and loop until isTruncated is false | Fine-grained control over each page, early exit on a condition |
| Paginator | The SDK manages the continuation token; iterate with for try await | Simpler code when you want to process all objects without managing tokens |
List objects with a paginator
listObjectsV2Paginator iterates through all pages automatically, with the SDK managing the continuation token for you.
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
do {
let region = "cn-hangzhou"
let bucket = "examplebucket"
let endpoint: String? = nil
let credentialsProvider = EnvironmentCredentialsProvider()
let config = Configuration.default()
.withRegion(region)
.withCredentialsProvider(credentialsProvider)
if let endpoint = endpoint {
config.withEndpoint(endpoint)
}
let client = Client(config)
// Create the paginator. No request is sent until you iterate.
let paginator = client.listObjectsV2Paginator(
ListObjectsV2Request(bucket: bucket)
)
// Each iteration fetches one page.
for try await page in paginator {
for content in page.contents ?? [] {
print("key: \(content.key ?? ""), size: \(String(describing: content.size)), last modified: \(String(describing: content.lastModified))")
}
}
} catch {
print("error: \(error)")
}
}
}What's next
Complete sample code: GitHub sample
API reference: ListObjectsV2