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

S3: Delete Multiple Objects and Check Per-Object Errors

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.

Sends an explicit DeleteObjects request with Http.HttpStr and receives the original HttpResponse. XML APIs safely serialize up to 1,000 object identifiers. The request uses quiet mode; successful entries may be absent. HTTP 200 can still contain per-object errors, so every Error element is inspected before reporting success.

The sample uses Crypt2 to sign this fixed POST /?delete= request with SigV4, including Content-MD5, the SHA-256 payload hash, date, and optional session token. Keep the system clock accurate. Do not alter signed components after signing. This signing block is specific to this operation, not a general URL canonicalizer. See AWS header-signing rules.

Requires s3:DeleteObject, and s3:DeleteObjectVersion for explicit versions. Version-specific deletion is permanent. Without a version ID, a versioning-enabled bucket normally gains delete markers instead. Missing keys count as successful deletes. MFA Delete, retention, and legal holds may affect results. Retry only failed identifiers when appropriate, rather than repeating successful versioned deletes.

AWS reference

Chilkat Objective-C Downloads

Objective-C
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <NSString.h>
#import <CkoXml.h>
#import <CkoDateTime.h>
#import <CkoCrypt2.h>
#import <CkoHttpResponse.h>

BOOL success = NO;

CkoStringBuilder *stringCompare = [[CkoStringBuilder alloc] init];
//  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.
CkoJsonObject *credentials = [[CkoJsonObject alloc] init];
credentials.Strict = YES;
success = [credentials LoadFile: @"qa_data/aws/s3.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not load private S3 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;
}

CkoHttp *http = [[CkoHttp alloc] init];
http.AwsAccessKey = [credentials StringOf: @"access_key"];
http.AwsSecretKey = [credentials StringOf: @"secret_key"];
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;
    }

    http.AwsSessionToken = [credentials StringOf: @"session_token"];
}

//  Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
//  Set the actual bucket region, not the caller's location.
NSString *region = @"us-west-2";
http.AwsRegion = region;
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[endpoint Append: @"s3."];
[endpoint Append: region];
[endpoint Append: @".amazonaws.com"];
http.AwsEndpoint = [endpoint GetAsString];
http.RequireSslCertVerify = YES;
http.FollowRedirects = NO;
//  A region redirect is not success. Correct the endpoint and signing region.
NSString *bucketName = @"your-bucket-name";
CkoXml *deleteRequest = [[CkoXml alloc] init];
deleteRequest.Tag = @"Delete";
[deleteRequest AddAttribute: @"xmlns" value: @"http://s3.amazonaws.com/doc/2006-03-01/"];
[deleteRequest UpdateChildContent: @"Quiet" value: @"true"];
//  XML APIs escape key text. Do NOT URL-encode keys in this XML body.
[deleteRequest UpdateChildContent: @"Object[0]|Key" value: @"images/seahorse.jpg"];
[deleteRequest UpdateChildContent: @"Object[1]|Key" value: @"images/starfish.jpg"];
//  For permanent deletion of a specific version, add Object[i]|VersionId
//  deliberately. Use separate XML elements, not an embedded string convention.
if (([[deleteRequest NumChildrenHavingTag: @"Object"] intValue] < 1) || ([[deleteRequest NumChildrenHavingTag: @"Object"] intValue] > 1000)) {
    NSLog(@"%@",@"Use a batch of 1 to 1,000 object identifiers.");
    return;
}

NSString *requestBody = [deleteRequest GetXml];
//  Sign this exact POST /?delete= request, including its UTF-8 body and MD5.
//  Do not change signed headers, body, endpoint, or query after signing.
CkoStringBuilder *host = [[CkoStringBuilder alloc] init];
[host Append: bucketName];
[host Append: @"."];
[host Append: [endpoint GetAsString]];
CkoDateTime *now = [[CkoDateTime alloc] init];
success = [now SetFromCurrentSystemTime];
if (success != YES) {
    NSLog(@"%@",@"Could not read system time.");
    return;
}

CkoStringBuilder *timestamp = [[CkoStringBuilder alloc] init];
[timestamp Append: [now GetAsTimestamp: NO]];
int removedDashes = [[timestamp Replace: @"-" replacement: @""] intValue];
int removedColons = [[timestamp Replace: @":" replacement: @""] intValue];
NSString *amzDate = [timestamp GetAsString];
NSString *dateStamp = [timestamp GetRange: [NSNumber numberWithInt: 0] numChars: [NSNumber numberWithInt: 8] removeFlag: NO];
CkoCrypt2 *crypt = [[CkoCrypt2 alloc] init];
crypt.Charset = @"utf-8";
crypt.HashAlgorithm = @"md5";
crypt.EncodingMode = @"base64";
NSString *contentMd5 = [crypt HashStringENC: requestBody];
if (crypt.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not hash delete body.");
    return;
}

crypt.HashAlgorithm = @"sha256";
crypt.EncodingMode = @"hexlower";
NSString *payloadHash = [crypt HashStringENC: requestBody];
if (crypt.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not hash delete body.");
    return;
}

CkoStringBuilder *signedHeaders = [[CkoStringBuilder alloc] init];
[signedHeaders Append: @"content-md5;host;x-amz-content-sha256;x-amz-date"];
CkoStringBuilder *canonical = [[CkoStringBuilder alloc] init];
[canonical Append: @"POST\n/\ndelete=\ncontent-md5:"];
[canonical Append: contentMd5];
[canonical Append: @"\nhost:"];
[canonical Append: [host GetAsString]];
[canonical Append: @"\nx-amz-content-sha256:"];
[canonical Append: payloadHash];
[canonical Append: @"\nx-amz-date:"];
[canonical Append: amzDate];
[canonical Append: @"\n"];
if ([credentials HasMember: @"session_token"] == YES) {
    [signedHeaders Append: @";x-amz-security-token"];
    [canonical Append: @"x-amz-security-token:"];
    [canonical Append: [credentials StringOf: @"session_token"]];
    [canonical Append: @"\n"];
    [http SetRequestHeader: @"x-amz-security-token" value: [credentials StringOf: @"session_token"]];
}

[canonical Append: @"\n"];
[canonical Append: [signedHeaders GetAsString]];
[canonical Append: @"\n"];
[canonical Append: payloadHash];
NSString *canonicalHash = [crypt HashStringENC: [canonical GetAsString]];
if (crypt.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not hash canonical request.");
    return;
}

CkoStringBuilder *scope = [[CkoStringBuilder alloc] init];
[scope Append: dateStamp];
[scope Append: @"/"];
[scope Append: region];
[scope Append: @"/s3/aws4_request"];
CkoStringBuilder *stringToSign = [[CkoStringBuilder alloc] init];
[stringToSign Append: @"AWS4-HMAC-SHA256\n"];
[stringToSign Append: amzDate];
[stringToSign Append: @"\n"];
[stringToSign Append: [scope GetAsString]];
[stringToSign Append: @"\n"];
[stringToSign Append: canonicalHash];
CkoStringBuilder *initialKey = [[CkoStringBuilder alloc] init];
[initialKey Append: @"AWS4"];
[initialKey Append: [credentials StringOf: @"secret_key"]];
crypt.MacAlgorithm = @"hmac";
success = [crypt SetMacKeyString: [initialKey GetAsString]];
if (success != YES) {
    NSLog(@"%@",@"Could not set signing key.");
    return;
}

NSString *derivedKey = [crypt MacStringENC: dateStamp];
if (crypt.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not derive date signing key.");
    return;
}

success = [crypt SetMacKeyEncoded: derivedKey encoding: @"hex"];
if (success != YES) {
    NSLog(@"%@",@"Could not set derived signing key.");
    return;
}

derivedKey = [crypt MacStringENC: region];
if (crypt.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not derive signing key.");
    return;
}

success = [crypt SetMacKeyEncoded: derivedKey encoding: @"hex"];
if (success != YES) {
    NSLog(@"%@",@"Could not set derived signing key.");
    return;
}

derivedKey = [crypt MacStringENC: @"s3"];
if (crypt.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not derive signing key.");
    return;
}

success = [crypt SetMacKeyEncoded: derivedKey encoding: @"hex"];
if (success != YES) {
    NSLog(@"%@",@"Could not set derived signing key.");
    return;
}

derivedKey = [crypt MacStringENC: @"aws4_request"];
if (crypt.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not derive signing key.");
    return;
}

success = [crypt SetMacKeyEncoded: derivedKey encoding: @"hex"];
if (success != YES) {
    NSLog(@"%@",@"Could not set final signing key.");
    return;
}

NSString *signature = [crypt MacStringENC: [stringToSign GetAsString]];
if (crypt.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Could not sign delete request.");
    return;
}

CkoStringBuilder *authorization = [[CkoStringBuilder alloc] init];
[authorization Append: @"AWS4-HMAC-SHA256 Credential="];
[authorization Append: [credentials StringOf: @"access_key"]];
[authorization Append: @"/"];
[authorization Append: [scope GetAsString]];
[authorization Append: @", SignedHeaders="];
[authorization Append: [signedHeaders GetAsString]];
[authorization Append: @", Signature="];
[authorization Append: signature];
[http SetRequestHeader: @"Authorization" value: [authorization GetAsString]];
[http SetRequestHeader: @"Content-MD5" value: contentMd5];
[http SetRequestHeader: @"x-amz-content-sha256" value: payloadHash];
[http SetRequestHeader: @"x-amz-date" value: amzDate];
CkoStringBuilder *requestUrl = [[CkoStringBuilder alloc] init];
[requestUrl Append: @"https://"];
[requestUrl Append: [host GetAsString]];
[requestUrl Append: @"/?delete="];
CkoHttpResponse *response = [[CkoHttpResponse alloc] init];
success = [http HttpStr: @"POST" url: [requestUrl GetAsString] bodyStr: requestBody charset: @"utf-8" contentType: @"application/xml" response: response];
if (success != YES) {
    NSLog(@"%@%d",@"Request failed (transport or S3 error). HTTP status: ",[http.LastStatus intValue]);
    //  Inspect LastErrorText privately. Do not log credentials or signed URLs.
    return;
}

if ([response.StatusCode intValue] != 200) {
    NSLog(@"%@%d",@"Unexpected HTTP status: ",[response.StatusCode intValue]);
    return;
}

//  HTTP 200 can contain per-object errors. Inspect the actual XML body.
CkoXml *xml = [[CkoXml alloc] init];
success = [xml LoadXml: response.BodyStr];
if (success != YES) {
    NSLog(@"%@",@"Invalid XML response.");
    return;
}

[stringCompare SetString: xml.Tag];
BOOL stringMatch4 = [stringCompare ContentsEqual: @"DeleteResult" caseSensitive: YES];
if (stringMatch4 != YES) {
    NSLog(@"%@",@"Unexpected XML response root.");
    return;
}

int failures = [[xml NumChildrenHavingTag: @"Error"] intValue];
int i = 0;
while ((i < failures)) {
    xml.I = [NSNumber numberWithInt: i];
    NSLog(@"%@%@",@"Failed key: ",[xml GetChildContent: @"Error[i]|Key"]);
    NSLog(@"%@%@",@"Error code: ",[xml GetChildContent: @"Error[i]|Code"]);
    i = i + 1;
}

if (failures != 0) {
    NSLog(@"%@",@"One or more objects were not deleted. Retry only appropriate failed identifiers.");
    return;
}

//  Quiet=true means success entries need not be returned.
NSLog(@"%@",@"Delete batch succeeded with no reported object errors.");