Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.6.0+

S3: List More Than 1,000 Objects with Pagination

See more S3 - HTTP Examples

Uses Chilkat.Http with Amazon S3 general purpose buckets and Signature Version 4. These examples do not cover directory buckets/S3 Express, access-point ARNs, Outposts, or other specialized endpoints. They target the commercial AWS partition; other partitions need their documented endpoint suffix.

Load private qa_data/aws/s3.json containing nonempty string fields access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials. These samples do not discover AWS profiles or refresh credentials. Set the bucket's actual region and replace sample bucket names and object keys. TLS certificate verification is explicitly enabled. Keep detailed HTTP diagnostics private because they can contain credentials or presigned URLs.

Uses S3_ListBucketObjects with list-type=2 to request ListObjectsV2. Follows opaque NextContinuationToken values while IsTruncated is true, including empty pages; detects missing/repeated tokens and stops at 10,000 pages with incomplete-results status. Requires s3:ListBucket.

Requests encoding-type=url so keys containing XML-incompatible characters can be represented. Decode returned keys exactly once before reusing them. Query values are encoded separately. Sizes remain decimal strings to preserve large values; LastModified is an ISO 8601 UTC timestamp, not RFC 822. Owner.DisplayName is not used. Listing pages are not a single snapshot if objects change during enumeration.

AWS reference

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    let stringCompare = CkoStringBuilder()!
    //  This example requires the Chilkat API to have been previously unlocked.
    //  See Global Unlock Sample for sample code.
    //  Load private credentials; never put access keys or session tokens in source.
    let credentials = CkoJsonObject()!
    credentials.strict = true
    success = credentials.loadFile(path: "qa_data/aws/s3.json")
    if success != true {
        print("Could not load private S3 credentials.")
        return
    }

    stringCompare.setString(value: credentials.string(of: "access_key"))
    var stringMatch1: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
    if (credentials.jsonType(of: "access_key").intValue != 1) || (stringMatch1 == true) {
        print("Missing or invalid access_key.")
        return
    }

    stringCompare.setString(value: credentials.string(of: "secret_key"))
    var stringMatch2: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
    if (credentials.jsonType(of: "secret_key").intValue != 1) || (stringMatch2 == true) {
        print("Missing or invalid secret_key.")
        return
    }

    let http = CkoHttp()!
    http.awsAccessKey = credentials.string(of: "access_key")
    http.awsSecretKey = credentials.string(of: "secret_key")
    if credentials.hasMember(jsonPath: "session_token") == true {
        stringCompare.setString(value: credentials.string(of: "session_token"))
        var stringMatch3: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
        if (credentials.jsonType(of: "session_token").intValue != 1) || (stringMatch3 == true) {
            print("session_token must be a nonempty string when supplied.")
            return
        }

        http.awsSessionToken = credentials.string(of: "session_token")
    }

    //  Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
    //  Set the actual bucket region, not the caller's location.
    var region: String? = "us-west-2"
    http.awsRegion = region
    let endpoint = CkoStringBuilder()!
    endpoint.append(value: "s3.")
    endpoint.append(value: region)
    endpoint.append(value: ".amazonaws.com")
    http.awsEndpoint = endpoint.getAsString()
    http.requireSslCertVerify = true
    http.followRedirects = false
    //  A region redirect is not success. Correct the endpoint and signing region.
    var bucketName: String? = "your-bucket-name"
    let bucketPath = CkoStringBuilder()!
    let encoded = CkoStringBuilder()!
    let xml = CkoXml()!
    let seenTokens = CkoHashtable()!
    var token: String? = ""
    var more: Bool = true
    var page: Int = 0
    while (more == true) {
        if page == 10000 {
            print("Page limit reached; listing is incomplete.")
            return
        }

        page = page + 1
        bucketPath.setString(value: bucketName)
        bucketPath.append(value: "?list-type=2&max-keys=1000&encoding-type=url")
        stringCompare.setString(value: token)
        var stringMatch4: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
        if stringMatch4 != true {
            encoded.setString(value: token)
            bucketPath.append(value: "&continuation-token=")
            bucketPath.append(value: encoded.getEncoded(encoding: "url", charset: "utf-8"))
        }

        var xmlStr: String? = http.s3_ListBucketObjects(bucketName: bucketPath.getAsString())
        if http.lastMethodSuccess != true {
            print("Request failed (transport or S3 error). HTTP status: \(http.lastStatus.intValue)")
            //  Inspect LastErrorText privately. Do not log credentials or signed URLs.
            return
        }

        if http.lastStatus.intValue != 200 {
            print("Unexpected HTTP status: \(http.lastStatus.intValue)")
            return
        }

        success = xml.load(xmlData: xmlStr)
        if success != true {
            print("Invalid XML response.")
            return
        }

        stringCompare.setString(value: xml.tag)
        var stringMatch5: Bool = stringCompare.contentsEqual(str: "ListBucketResult", caseSensitive: true)
        if stringMatch5 != true {
            print("Unexpected XML response root.")
            return
        }

        stringCompare.setString(value: xml.getChildContent(tagPath: "EncodingType"))
        var stringMatch6: Bool = stringCompare.contentsEqual(str: "url", caseSensitive: true)
        if stringMatch6 != true {
            print("Expected URL-encoded listing keys.")
            return
        }

        var i: Int = 0
        var count: Int = xml.numChildrenHavingTag(tag: "Contents").intValue
        while (i < count) {
            xml.i = i
            //  Decode keys exactly once. Sizes remain decimal strings (not int).
            var itemKey: String? = http.urlDecode(str: xml.getChildContent(tagPath: "Contents[i]|Key"))
            stringCompare.setString(value: itemKey)
            var stringMatch7: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
            if (http.lastMethodSuccess != true) || (stringMatch7 == true) {
                print("Invalid object key.")
                return
            }

            var size: String? = xml.getChildContent(tagPath: "Contents[i]|Size")
            stringCompare.setString(value: size)
            var stringMatch8: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
            if (xml.lastMethodSuccess != true) || (stringMatch8 == true) {
                print("Incomplete object entry.")
                return
            }

            var modified: String? = xml.getChildContent(tagPath: "Contents[i]|LastModified")
            stringCompare.setString(value: modified)
            var stringMatch9: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
            if (xml.lastMethodSuccess != true) || (stringMatch9 == true) {
                print("Incomplete object entry.")
                return
            }

            print("Key: \(itemKey!)")
            print("Bytes: \(size!)")
            //  S3 returns ISO 8601, not RFC 822. Keep the original UTC timestamp.
            print("Last modified (UTC): \(modified!)")
            i = i + 1
        }

        var truncated: String? = xml.getChildContent(tagPath: "IsTruncated")
        stringCompare.setString(value: truncated)
        var stringMatch10: Bool = stringCompare.contentsEqual(str: "true", caseSensitive: true)
        stringCompare.setString(value: truncated)
        var stringMatch11: Bool = stringCompare.contentsEqual(str: "false", caseSensitive: true)
        if (stringMatch10 != true) && (stringMatch11 != true) {
            print("Missing or invalid IsTruncated; listing is incomplete.")
            return
        }

        more = false
        stringCompare.setString(value: truncated)
        var stringMatch12: Bool = stringCompare.contentsEqual(str: "true", caseSensitive: true)
        if stringMatch12 == true {
            token = xml.getChildContent(tagPath: "NextContinuationToken")
            stringCompare.setString(value: token)
            var stringMatch13: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
            if (xml.lastMethodSuccess != true) || (stringMatch13 == true) {
                print("Missing continuation token; listing is incomplete.")
                return
            }

            if seenTokens.contains(key: token) == true {
                print("Repeated continuation token; listing is incomplete.")
                return
            }

            success = seenTokens.addStr(key: token, value: "seen")
            if success != true {
                print("Could not track pagination.")
                return
            }

            more = true
        }

    }

    print("Object listing complete.")

}