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

Amazon SNS: List All SMS Origination Numbers

See more Amazon SNS Examples

Uses the current Amazon SNS Query API (Version=2010-03-31) through Chilkat.Rest and AuthAws, with HTTPS, Signature Version 4, and service sns. The API version date remains current. Action and input parameters are URL-encoded into a POST body, avoiding message text and recipient addresses in the URL. Set the actual region once; other AWS partitions need their documented endpoint suffix and ARN partition.

Load private qa_data/aws/sns.json with nonempty string fields access_key, secret_key, and session_token when using temporary credentials. Prefer short-lived role credentials. This sample does not discover profiles, obtain credentials, or refresh them automatically. The session token is included in the signed form body on every request. A Socket explicitly enables TLS certificate verification before passing the connection to Rest.

Checks setup calls, transport completion, HTTP status, XML parsing, result root, and required fields. Normal output includes identifiers, not full messages or headers. Keep detailed diagnostics private. For retryable failures, use bounded backoff with jitter in the application; these examples do not automatically retry writes. A Publish timeout can leave an accepted message and retrying a standard-topic/SMS publish can duplicate it. A returned MessageId confirms SNS acceptance, not subscriber or handset delivery.

Paginates dedicated origination numbers with MaxResults=30, the API maximum. An inventory entry alone does not establish support for every destination country or message type. Registration and regional requirements still apply.

Required IAM actions: sns:ListOriginationNumbers. Related SQS/KMS permissions are separate.

AWS references: ListOriginationNumbers

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    let stringCompare = CkoStringBuilder()!
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  Private credentials; do not put this file in public web content or source control.
    let credentials = CkoJsonObject()!
    credentials.strict = true
    success = credentials.loadFile(path: "qa_data/aws/sns.json")
    if success != true {
        print("Could not load private SNS 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
    }

    var region: String? = "us-west-2"
    let endpoint = CkoStringBuilder()!
    endpoint.append(value: "sns.")
    endpoint.append(value: region)
    endpoint.append(value: ".amazonaws.com")
    let aws = CkoAuthAws()!
    aws.accessKey = credentials.string(of: "access_key")
    aws.secretKey = credentials.string(of: "secret_key")
    aws.region = region
    aws.serviceName = "sns"
    aws.signatureVersion = 4
    let rest = CkoRest()!
    rest.connectTimeoutMs = 20000
    rest.idleTimeoutMs = 60000
    rest.verboseLogging = false
    success = rest.setAuthAws(authProvider: aws)
    if success != true {
        print("Could not configure AWS signing.")
        return
    }

    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
        }

    }

    let xml = CkoXml()!
    xml.strict = true
    var value: String?
    var responseXml: String?
    //  Explicit certificate verification; keep this Socket alive while Rest uses it.
    let connection = CkoSocket()!
    connection.requireSslCertVerify = true
    connection.maxReadIdleMs = 60000
    connection.maxSendIdleMs = 60000
    success = connection.connect(hostname: endpoint.getAsString(), port: 443, ssl: true, maxWaitMs: 20000)
    if success != true {
        print("TLS connection failed; inspect diagnostics privately.")
        return
    }

    success = rest.useConnection(connection: connection, autoReconnect: true)
    if success != true {
        print("Could not attach TLS connection.")
        return
    }

    let seenTokens = CkoHashtable()!
    var nextToken: String? = ""
    var more: Bool = true
    var page: Int = 0
    while (more == true) {
        if page == 10000 {
            print("Page bound reached; enumeration incomplete.")
            return
        }

        page = page + 1
        success = rest.clearAllQueryParams()
        if success != true {
            print("Could not clear parameters from the previous request.")
            return
        }

        //  Build a fresh form for each request; do not retain parameters from a previous action.
        //  AddQueryParam encodes raw values into the POST body. Do not pre-encode them.
        success = rest.addQueryParam(name: "Action", value: "ListOriginationNumbers")
        if success != true {
            print("Could not set Action.")
            return
        }

        success = rest.addQueryParam(name: "Version", value: "2010-03-31")
        if success != true {
            print("Could not set Version.")
            return
        }

        //  Include temporary credentials in the signed form body on every request.
        if credentials.hasMember(jsonPath: "session_token") == true {
            success = rest.addQueryParam(name: "X-Amz-Security-Token", value: credentials.string(of: "session_token"))
            if success != true {
                print("Could not set X-Amz-Security-Token.")
                return
            }

        }

        success = rest.addQueryParam(name: "MaxResults", value: "30")
        if success != true {
            print("Could not set MaxResults.")
            return
        }

        stringCompare.setString(value: nextToken)
        var stringMatch4: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
        if stringMatch4 != true {
            success = rest.addQueryParam(name: "NextToken", value: nextToken)
            if success != true {
                print("Could not set NextToken.")
                return
            }

        }

        responseXml = rest.fullRequestFormUrlEncoded(httpVerb: "POST", uriPath: "/")
        if rest.lastMethodSuccess != true {
            print("Request did not complete. Inspect diagnostics privately.")
            return
        }

        success = xml.load(xmlData: responseXml)
        if rest.responseStatusCode.intValue != 200 {
            print("SNS HTTP status: \(rest.responseStatusCode.intValue)")
            if success == true {
                value = xml.getChildContent(tagPath: "Error|Code")
                if xml.lastMethodSuccess == true {
                    print("AWS error code: \(value!)")
                }

                value = xml.getChildContent(tagPath: "RequestId")
                if xml.lastMethodSuccess == true {
                    print("AWS request ID: \(value!)")
                }

            }

            //  Full messages, headers, and signing diagnostics may contain private data.
            return
        }

        if success != true {
            print("Expected a well-formed XML response.")
            return
        }

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

        value = xml.getChildContent(tagPath: "ResponseMetadata|RequestId")
        stringCompare.setString(value: value)
        var stringMatch6: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
        if (xml.lastMethodSuccess != true) || (stringMatch6 == true) {
            print("Missing or empty ResponseMetadata|RequestId.")
            return
        }

        print("AWS request ID: \(value!)")
        if xml.hasChild(withTag: "ListOriginationNumbersResult") != true {
            print("Missing result.")
            return
        }

        var itemIndex: Int = 0
        while (itemIndex < xml.numChildren(at: "ListOriginationNumbersResult|PhoneNumbers").intValue) {
            xml.i = itemIndex
            value = xml.getChildContent(tagPath: "ListOriginationNumbersResult|PhoneNumbers|member[i]|PhoneNumber")
            stringCompare.setString(value: value)
            var stringMatch7: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
            if (xml.lastMethodSuccess != true) || (stringMatch7 == true) {
                print("Missing or empty ListOriginationNumbersResult|PhoneNumbers|member[i]|PhoneNumber.")
                return
            }

            print("PhoneNumber: \(value!)")
            value = xml.getChildContent(tagPath: "ListOriginationNumbersResult|PhoneNumbers|member[i]|PhoneNumberArn")
            stringCompare.setString(value: value)
            var stringMatch8: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
            if (xml.lastMethodSuccess != true) || (stringMatch8 == true) {
                print("Missing or empty ListOriginationNumbersResult|PhoneNumbers|member[i]|PhoneNumberArn.")
                return
            }

            print("PhoneNumberArn: \(value!)")
            value = xml.getChildContent(tagPath: "ListOriginationNumbersResult|PhoneNumbers|member[i]|Iso2CountryCode")
            stringCompare.setString(value: value)
            var stringMatch9: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
            if (xml.lastMethodSuccess != true) || (stringMatch9 == true) {
                print("Missing or empty ListOriginationNumbersResult|PhoneNumbers|member[i]|Iso2CountryCode.")
                return
            }

            print("Iso2CountryCode: \(value!)")
            itemIndex = itemIndex + 1
        }

        nextToken = xml.getChildContent(tagPath: "ListOriginationNumbersResult|NextToken")
        if xml.lastMethodSuccess != true {
            nextToken = ""
        }

        more = false
        stringCompare.setString(value: nextToken)
        var stringMatch10: Bool = stringCompare.contentsEqual(str: "", caseSensitive: true)
        if stringMatch10 != true {
            if seenTokens.contains(key: nextToken) == true {
                print("Repeated pagination token; enumeration incomplete.")
                return
            }

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

            more = true
        }

    }

    print("Example completed.")

}