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

Amazon SNS: Publish a Batch and Handle Partial Failures

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.

Sends two uniquely identified messages (the API allows at most ten). Checks both Successful and Failed collections even on HTTP 200, rejects unknown/duplicate/missing result IDs, and reports SenderFault. No attributes are included; their sizes would also count against the combined limit. Retry only appropriate failed entries with bounded backoff, never the successful entries. A transport timeout or malformed response has uncertain outcomes and can cause duplicates on a standard topic.

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

AWS references: PublishBatch

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 <CkoBinData.h>
#import <CkoSocket.h>
#import <CkoHashtable.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;
NSString *responseXml = 0;
NSString *topicArn = @"arn:aws:sns:us-west-2:123456789012:chilkat-standard-example";
CkoStringBuilder *topic = [[CkoStringBuilder alloc] init];
[topic Append: topicArn];
CkoStringBuilder *arnPrefix = [[CkoStringBuilder alloc] init];
[arnPrefix Append: @"arn:aws:sns:"];
[arnPrefix Append: region];
[arnPrefix Append: @":"];
if ([topic StartsWith: [arnPrefix GetAsString] caseSensitive: YES] != YES) {
    NSLog(@"%@",@"Select an SNS topic ARN in the configured region and commercial AWS partition.");
    return;
}

if ([topic EndsWith: @".fifo" caseSensitive: YES] == YES) {
    NSLog(@"%@",@"This example uses a standard topic. FIFO publishing needs group/deduplication handling.");
    return;
}

NSString *firstMessage = @"Order 123 created.";
NSString *secondMessage = @"Order 124 created.";
CkoBinData *payloadBytes = [[CkoBinData alloc] init];
success = [payloadBytes AppendString: firstMessage charset: @"utf-8"];
if (success != YES) {
    NSLog(@"%@",@"Could not encode payload.");
    return;
}

success = [payloadBytes AppendString: secondMessage charset: @"utf-8"];
if (success != YES) {
    NSLog(@"%@",@"Could not encode payload.");
    return;
}

if (([payloadBytes.NumBytes intValue] == 0) || ([payloadBytes.NumBytes intValue] > 262144)) {
    NSLog(@"%@",@"This example requires a nonempty payload within 256 KiB; the topic may impose a lower limit.");
    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 parameters from a previous action.
//  AddQueryParam encodes raw values into the POST body. Do not pre-encode them.
success = [rest AddQueryParam: @"Action" value: @"PublishBatch"];
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: @"TopicArn" value: topicArn];
if (success != YES) {
    NSLog(@"%@",@"Could not set TopicArn.");
    return;
}

success = [rest AddQueryParam: @"PublishBatchRequestEntries.member.1.Id" value: @"entry-1"];
if (success != YES) {
    NSLog(@"%@",@"Could not set PublishBatchRequestEntries.member.1.Id.");
    return;
}

success = [rest AddQueryParam: @"PublishBatchRequestEntries.member.1.Message" value: firstMessage];
if (success != YES) {
    NSLog(@"%@",@"Could not set PublishBatchRequestEntries.member.1.Message.");
    return;
}

success = [rest AddQueryParam: @"PublishBatchRequestEntries.member.2.Id" value: @"entry-2"];
if (success != YES) {
    NSLog(@"%@",@"Could not set PublishBatchRequestEntries.member.2.Id.");
    return;
}

success = [rest AddQueryParam: @"PublishBatchRequestEntries.member.2.Message" value: secondMessage];
if (success != YES) {
    NSLog(@"%@",@"Could not set PublishBatchRequestEntries.member.2.Message.");
    return;
}

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 stringMatch4 = [stringCompare ContentsEqual: @"PublishBatchResponse" caseSensitive: YES];
if (stringMatch4 != YES) {
    NSLog(@"%@",@"Unexpected SNS response element.");
    return;
}

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

NSLog(@"%@%@",@"AWS request ID: ",value);
CkoHashtable *outcomes = [[CkoHashtable alloc] init];
int batchIndex = 0;
int failedCount = 0;
batchIndex = 0;
while ((batchIndex < [[xml NumChildrenAt: @"PublishBatchResult|Successful"] intValue])) {
    xml.I = [NSNumber numberWithInt: batchIndex];
    value = [xml GetChildContent: @"PublishBatchResult|Successful|member[i]|Id"];
    [stringCompare SetString: value];
    BOOL stringMatch6 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
    if ((xml.LastMethodSuccess != YES) || (stringMatch6 == YES)) {
        NSLog(@"%@",@"Missing or empty PublishBatchResult|Successful|member[i]|Id.");
        return;
    }

    NSString *entryId = value;
    [stringCompare SetString: entryId];
    BOOL stringMatch7 = [stringCompare ContentsEqual: @"entry-1" caseSensitive: YES];
    [stringCompare SetString: entryId];
    BOOL stringMatch8 = [stringCompare ContentsEqual: @"entry-2" caseSensitive: YES];
    if ((stringMatch7 != YES) && (stringMatch8 != YES)) {
        NSLog(@"%@",@"Unknown batch result ID; outcome requires reconciliation.");
        return;
    }

    if ([outcomes Contains: entryId] == YES) {
        NSLog(@"%@",@"Duplicate batch result ID; outcome requires reconciliation.");
        return;
    }

    success = [outcomes AddStr: entryId value: @"seen"];
    if (success != YES) {
        NSLog(@"%@",@"Could not track batch result.");
        return;
    }

    value = [xml GetChildContent: @"PublishBatchResult|Successful|member[i]|MessageId"];
    [stringCompare SetString: value];
    BOOL stringMatch9 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
    if ((xml.LastMethodSuccess != YES) || (stringMatch9 == YES)) {
        NSLog(@"%@",@"Missing or empty PublishBatchResult|Successful|member[i]|MessageId.");
        return;
    }

    NSLog(@"%@%@%@%@",@"Successful entry: ",entryId,@" / ",value);
    batchIndex = batchIndex + 1;
}

batchIndex = 0;
while ((batchIndex < [[xml NumChildrenAt: @"PublishBatchResult|Failed"] intValue])) {
    xml.I = [NSNumber numberWithInt: batchIndex];
    value = [xml GetChildContent: @"PublishBatchResult|Failed|member[i]|Id"];
    [stringCompare SetString: value];
    BOOL stringMatch10 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
    if ((xml.LastMethodSuccess != YES) || (stringMatch10 == YES)) {
        NSLog(@"%@",@"Missing or empty PublishBatchResult|Failed|member[i]|Id.");
        return;
    }

    NSString *entryId = value;
    [stringCompare SetString: entryId];
    BOOL stringMatch11 = [stringCompare ContentsEqual: @"entry-1" caseSensitive: YES];
    [stringCompare SetString: entryId];
    BOOL stringMatch12 = [stringCompare ContentsEqual: @"entry-2" caseSensitive: YES];
    if ((stringMatch11 != YES) && (stringMatch12 != YES)) {
        NSLog(@"%@",@"Unknown batch result ID; outcome requires reconciliation.");
        return;
    }

    if ([outcomes Contains: entryId] == YES) {
        NSLog(@"%@",@"Duplicate batch result ID; outcome requires reconciliation.");
        return;
    }

    success = [outcomes AddStr: entryId value: @"seen"];
    if (success != YES) {
        NSLog(@"%@",@"Could not track batch result.");
        return;
    }

    value = [xml GetChildContent: @"PublishBatchResult|Failed|member[i]|Code"];
    [stringCompare SetString: value];
    BOOL stringMatch13 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
    if ((xml.LastMethodSuccess != YES) || (stringMatch13 == YES)) {
        NSLog(@"%@",@"Missing or empty PublishBatchResult|Failed|member[i]|Code.");
        return;
    }

    NSLog(@"%@%@%@%@",@"Failed entry: ",entryId,@" / ",value);
    value = [xml GetChildContent: @"PublishBatchResult|Failed|member[i]|SenderFault"];
    [stringCompare SetString: value];
    BOOL stringMatch14 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
    if ((xml.LastMethodSuccess != YES) || (stringMatch14 == YES)) {
        NSLog(@"%@",@"Missing or empty PublishBatchResult|Failed|member[i]|SenderFault.");
        return;
    }

    [stringCompare SetString: value];
    BOOL stringMatch15 = [stringCompare ContentsEqual: @"true" caseSensitive: YES];
    [stringCompare SetString: value];
    BOOL stringMatch16 = [stringCompare ContentsEqual: @"false" caseSensitive: YES];
    if ((stringMatch15 != YES) && (stringMatch16 != YES)) {
        NSLog(@"%@",@"Invalid SenderFault value.");
        return;
    }

    NSLog(@"%@%@",@"Sender fault: ",value);
    failedCount = failedCount + 1;
    batchIndex = batchIndex + 1;
}

if (([outcomes Contains: @"entry-1"] != YES) || ([outcomes Contains: @"entry-2"] != YES)) {
    NSLog(@"%@",@"Missing batch outcomes; reconcile before retrying.");
    return;
}

NSLog(@"%@%d",@"Failed entries: ",failedCount);
NSLog(@"%@",@"Example completed.");