Sample code for 30+ languages & platforms
Objective-C Requires Chilkat v11.6.0+

Amazon SNS: Send an SMS Directly to an E.164 Phone Number

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.

Use an authorized recipient in E.164 format. New SMS accounts start in the regional SMS sandbox and can send only to verified destinations. Origination identities, country support, registration, spending limits and opt-out status can affect delivery. Confirm the appropriate configuration with SNS SMS sandbox guidance and SNS SMS sending guidance.

Messages can be segmented and billed as multiple SMS messages; encoding affects segment size. The sample chooses AWS.SNS.SMS.SMSType=Transactional for a transactional test message; choose a type appropriate to the actual use. A MessageId is not a delivery receipt. Direct SMS uses PhoneNumber without TopicArn or TargetArn. There is no need to create a topic or subscription for a direct send.

The local input check limits the message to 1,600 characters but does not predict segment count or cost. The example sets only PhoneNumber as its destination; it does not publish to a topic at the same time.

Required IAM action: sns:Publish. Grant only the intended resource access; direct SMS does not have a topic ARN resource. Topic policies and KMS key access can also affect requests.

AWS Publish reference

Chilkat Objective-C Downloads

Objective-C
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoAuthAws.h>
#import <CkoRest.h>
#import <CkoXml.h>
#import <CkoSocket.h>

BOOL success = NO;

CkoStringBuilder *stringCompare = [[CkoStringBuilder alloc] init];
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Private credentials; do not put this file in public web content or source control.
CkoJsonObject *credentials = [[CkoJsonObject alloc] init];
credentials.Strict = YES;
success = [credentials LoadFile: @"qa_data/aws/sns.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not load private SNS credentials.");
    return;
}

[stringCompare SetString: [credentials StringOf: @"access_key"]];
BOOL stringMatch1 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"access_key"] intValue] != 1) || (stringMatch1 == YES)) {
    NSLog(@"%@",@"Missing or invalid access_key.");
    return;
}

[stringCompare SetString: [credentials StringOf: @"secret_key"]];
BOOL stringMatch2 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"secret_key"] intValue] != 1) || (stringMatch2 == YES)) {
    NSLog(@"%@",@"Missing or invalid secret_key.");
    return;
}

NSString *region = @"us-west-2";
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[endpoint Append: @"sns."];
[endpoint Append: region];
[endpoint Append: @".amazonaws.com"];
CkoAuthAws *aws = [[CkoAuthAws alloc] init];
aws.AccessKey = [credentials StringOf: @"access_key"];
aws.SecretKey = [credentials StringOf: @"secret_key"];
aws.Region = region;
aws.ServiceName = @"sns";
aws.SignatureVersion = [NSNumber numberWithInt:4];
CkoRest *rest = [[CkoRest alloc] init];
rest.ConnectTimeoutMs = [NSNumber numberWithInt:20000];
rest.IdleTimeoutMs = [NSNumber numberWithInt:60000];
rest.VerboseLogging = NO;
success = [rest SetAuthAws: aws];
if (success != YES) {
    NSLog(@"%@",@"Could not configure AWS signing.");
    return;
}

if ([credentials HasMember: @"session_token"] == YES) {
    [stringCompare SetString: [credentials StringOf: @"session_token"]];
    BOOL stringMatch3 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
    if (([[credentials JsonTypeOf: @"session_token"] intValue] != 1) || (stringMatch3 == YES)) {
        NSLog(@"%@",@"session_token must be a nonempty string when supplied.");
        return;
    }

}

CkoXml *xml = [[CkoXml alloc] init];
xml.Strict = YES;
NSString *value = 0;
//  Use an authorized recipient in E.164 format; this number is a placeholder.
NSString *phoneNumber = @"+15551234567";
CkoStringBuilder *phone = [[CkoStringBuilder alloc] init];
[phone Append: phoneNumber];
[stringCompare SetString: [phone GetRange: [NSNumber numberWithInt: 1] numChars: [NSNumber numberWithInt: 1] removeFlag: NO]];
BOOL stringMatch4 = [stringCompare ContentsEqual: @"0" caseSensitive: YES];
if (([phone StartsWith: @"+" caseSensitive: YES] != YES) || ([phone.Length intValue] < 2) || ([phone.Length intValue] > 16) || (stringMatch4 == YES)) {
    NSLog(@"%@",@"Use E.164: + followed by at most 15 digits, starting with a nonzero digit.");
    return;
}

CkoStringBuilder *digits = [[CkoStringBuilder alloc] init];
[digits Append: @"0123456789"];
int position = 1;
while ((position < [phone.Length intValue])) {
    if ([digits Contains: [phone GetRange: [NSNumber numberWithInt: position] numChars: [NSNumber numberWithInt: 1] removeFlag: NO] caseSensitive: YES] != YES) {
        NSLog(@"%@",@"Phone number must contain only + and digits.");
        return;
    }

    position = position + 1;
}

CkoStringBuilder *message = [[CkoStringBuilder alloc] init];
[message Append: @"This is a transactional test message from Amazon SNS."];
if (([message.Length intValue] == 0) || ([message.Length intValue] > 1600)) {
    NSLog(@"%@",@"Use a nonempty SMS message within the 1600-character Publish limit; AWS applies encoding and segmentation rules.");
    return;
}

//  Explicit certificate verification; keep this Socket alive while Rest uses it.
CkoSocket *connection = [[CkoSocket alloc] init];
connection.RequireSslCertVerify = YES;
connection.MaxReadIdleMs = [NSNumber numberWithInt:60000];
connection.MaxSendIdleMs = [NSNumber numberWithInt:60000];
success = [connection Connect: [endpoint GetAsString] port: [NSNumber numberWithInt: 443] ssl: YES maxWaitMs: [NSNumber numberWithInt: 20000]];
if (success != YES) {
    NSLog(@"%@",@"TLS connection failed; inspect diagnostics privately.");
    return;
}

success = [rest UseConnection: connection autoReconnect: YES];
if (success != YES) {
    NSLog(@"%@",@"Could not attach TLS connection.");
    return;
}

success = [rest ClearAllQueryParams];
if (success != YES) {
    NSLog(@"%@",@"Could not clear parameters from the previous request.");
    return;
}

//  Build a fresh form for each request; do not retain previous parameters.
//  AddQueryParam encodes raw values into the POST body. Do not pre-encode them.
success = [rest AddQueryParam: @"Action" value: @"Publish"];
if (success != YES) {
    NSLog(@"%@",@"Could not set Action.");
    return;
}

success = [rest AddQueryParam: @"Version" value: @"2010-03-31"];
if (success != YES) {
    NSLog(@"%@",@"Could not set Version.");
    return;
}

//  Include temporary credentials in the signed form body on every request.
if ([credentials HasMember: @"session_token"] == YES) {
    success = [rest AddQueryParam: @"X-Amz-Security-Token" value: [credentials StringOf: @"session_token"]];
    if (success != YES) {
        NSLog(@"%@",@"Could not set X-Amz-Security-Token.");
        return;
    }

}

success = [rest AddQueryParam: @"PhoneNumber" value: phoneNumber];
if (success != YES) {
    NSLog(@"%@",@"Could not set PhoneNumber.");
    return;
}

success = [rest AddQueryParamSb: @"Message" value: message];
if (success != YES) {
    NSLog(@"%@",@"Could not set SMS message.");
    return;
}

success = [rest AddQueryParam: @"MessageAttributes.entry.1.Name" value: @"AWS.SNS.SMS.SMSType"];
if (success != YES) {
    NSLog(@"%@",@"Could not set MessageAttributes.entry.1.Name.");
    return;
}

success = [rest AddQueryParam: @"MessageAttributes.entry.1.Value.DataType" value: @"String"];
if (success != YES) {
    NSLog(@"%@",@"Could not set MessageAttributes.entry.1.Value.DataType.");
    return;
}

success = [rest AddQueryParam: @"MessageAttributes.entry.1.Value.StringValue" value: @"Transactional"];
if (success != YES) {
    NSLog(@"%@",@"Could not set MessageAttributes.entry.1.Value.StringValue.");
    return;
}

NSString *responseXml = [rest FullRequestFormUrlEncoded: @"POST" uriPath: @"/"];
if (rest.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Request did not complete. Its outcome may be uncertain; reconcile before retrying.");
    return;
}

success = [xml LoadXml: responseXml];
if ([rest.ResponseStatusCode intValue] != 200) {
    NSLog(@"%@%d",@"SNS HTTP status: ",[rest.ResponseStatusCode intValue]);
    if (success == YES) {
        value = [xml GetChildContent: @"Error|Code"];
        if (xml.LastMethodSuccess == YES) {
            NSLog(@"%@%@",@"AWS error code: ",value);
        }

        value = [xml GetChildContent: @"RequestId"];
        if (xml.LastMethodSuccess == YES) {
            NSLog(@"%@%@",@"AWS request ID: ",value);
        }

    }

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

if (success != YES) {
    NSLog(@"%@",@"Expected a well-formed XML response.");
    return;
}

[stringCompare SetString: xml.Tag];
BOOL stringMatch5 = [stringCompare ContentsEqual: @"PublishResponse" caseSensitive: YES];
if (stringMatch5 != YES) {
    NSLog(@"%@",@"Unexpected SNS response element.");
    return;
}

value = [xml GetChildContent: @"ResponseMetadata|RequestId"];
[stringCompare SetString: value];
BOOL stringMatch6 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch6 == YES)) {
    NSLog(@"%@",@"Missing or empty ResponseMetadata|RequestId.");
    return;
}

NSLog(@"%@%@",@"AWS request ID: ",value);
value = [xml GetChildContent: @"PublishResult|MessageId"];
[stringCompare SetString: value];
BOOL stringMatch7 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch7 == YES)) {
    NSLog(@"%@",@"Missing or empty PublishResult|MessageId.");
    return;
}

NSLog(@"%@%@",@"Message ID: ",value);
NSLog(@"%@",@"SMS accepted by SNS; handset delivery is not confirmed.");