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

Amazon S3: Delete Multiple Objects and Check Each Result

See more S3 - REST Examples

Deletes the explicitly supplied objects. Load qa_data/aws/delete-objects.json with {"objects":[{"key":"documents/old.txt"},{"key":"documents/older.txt","version_id":"VERSION_ID"}]}. Supply 1–1000 unique entries per request. The example does not enumerate a prefix or automatically retry. Requires s3:DeleteObject and, for explicit versions, s3:DeleteObjectVersion.

Without versionId, an unversioned object is permanently removed; a versioned bucket normally creates a delete marker. Explicit data-version deletion is permanent. Retention, legal holds and MFA Delete can restrict deletion. Absent keys can still be acknowledged as deleted. HTTP 200 may contain per-object errors; each returned key/version is matched against the intended batch. Reconcile uncertain or missing results before any retry.

General purpose DeleteObjects uses Content-MD5. The tested AuthAws path omits that header, so this example explicitly constructs Signature Version 4 for the fixed POST /?delete= request and sends it through Rest. This is deliberately not a general URL signer. Do not change the body, hostname, query, or signed headers after signing, or attach AuthAws as a second signer.

For general purpose S3 buckets, using regional HTTPS endpoints and AWS Signature Version 4. Directory buckets (S3 Express), access points, Outposts, and other AWS partitions need their own endpoint/authentication rules. Use a bucket name without dots for these virtual-hosted TLS examples; see the path-style example for dotted names.

Provide current IAM credentials in a private qa_data/aws/s3.json file with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This file is explicitly loaded; these examples do not discover profiles or refresh credentials. Keep it outside public content and source control. The session token is included in the signed request. TLS certificate verification is enabled on the Socket used by Rest.

Transport success and HTTP success are different. Keep full diagnostics private; signed requests and presigned URLs can contain credentials or grant access. For retryable reads use bounded backoff with jitter. Before retrying a write with an uncertain outcome, check the resource state. Keep keys, upload IDs, version IDs, ETags, and large sizes as strings.

AWS DeleteObjects reference

Chilkat Objective-C Downloads

Objective-C
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoRest.h>
#import <CkoSocket.h>
#import <CkoXml.h>
#import <CkoHashtable.h>
#import <CkoDateTime.h>
#import <CkoCrypt2.h>

BOOL success = NO;

//  StringBuilder compares text by value in every generated language.
CkoStringBuilder *textCompare = [[CkoStringBuilder alloc] init];
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = NO;
//  Private configuration, not a file in public web content or source control.
//  Load current IAM credentials authorized for the S3 operation.
CkoJsonObject *credentials = [[CkoJsonObject alloc] init];
credentials.Strict = YES;
success = [credentials LoadFile: @"qa_data/aws/s3.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not load private AWS credentials.");
    return;
}

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

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

//  General purpose bucket in the commercial AWS partition.
NSString *region = @"us-west-2";
NSString *bucketName = @"amzn-s3-demo-bucket";
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
success = [endpoint Append: bucketName];
if (success != YES) {
    NSLog(@"%@",@"Could not build text.");
    return;
}

success = [endpoint Append: @"."];
if (success != YES) {
    NSLog(@"%@",@"Could not build text.");
    return;
}

success = [endpoint Append: @"s3."];
if (success != YES) {
    NSLog(@"%@",@"Could not build text.");
    return;
}

success = [endpoint Append: region];
if (success != YES) {
    NSLog(@"%@",@"Could not build text.");
    return;
}

success = [endpoint Append: @".amazonaws.com"];
if (success != YES) {
    NSLog(@"%@",@"Could not build text.");
    return;
}

CkoRest *rest = [[CkoRest alloc] init];
rest.ConnectTimeoutMs = [NSNumber numberWithInt:20000];
rest.IdleTimeoutMs = [NSNumber numberWithInt:60000];
//  Connect to the SAME hostname used for TLS verification and request signing.
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 the TLS connection.");
    return;
}

CkoXml *xml = [[CkoXml alloc] init];
xml.Strict = YES;
rest.Host = [endpoint GetAsString];
if ([credentials HasMember: @"session_token"] == YES) {
    if ([[credentials JsonTypeOf: @"session_token"] intValue] != 1) {
        NSLog(@"%@",@"session_token must be a string.");
        return;
    }

}

//  One explicit batch, at most 1000 objects. No prefix expansion or auto-retry.
CkoJsonObject *batch = [[CkoJsonObject alloc] init];
batch.Strict = YES;
success = [batch LoadFile: @"qa_data/aws/delete-objects.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not load the intended deletion batch.");
    return;
}

int count = [[batch SizeOfArray: @"objects"] intValue];
if ((count < 1) || (count > 1000)) {
    NSLog(@"%@",@"Supply 1 to 1000 objects in the batch.");
    return;
}

xml.Tag = @"Delete";
success = [xml AddAttribute: @"xmlns" value: @"http://s3.amazonaws.com/doc/2006-03-01/"];
if (success != YES) {
    NSLog(@"%@",@"Could not prepare the request.");
    return;
}

[xml UpdateChildContent: @"Quiet" value: @"false"];
CkoHashtable *requested = [[CkoHashtable alloc] init];
CkoJsonObject *identity = [[CkoJsonObject alloc] init];
int i = 0;
while ((i < count)) {
    batch.I = [NSNumber numberWithInt: i];
    xml.I = [NSNumber numberWithInt: i];
    [textCompare Clear];
    [textCompare SetString: [batch StringOf: @"objects[i].key"]];
    BOOL sameText3 = [textCompare ContentsEqual: @"" caseSensitive: YES];
    if (([[batch JsonTypeOf: @"objects[i].key"] intValue] != 1) || (sameText3 == YES)) {
        NSLog(@"%@",@"Each object needs a nonempty key.");
        return;
    }

    NSString *key = [batch StringOf: @"objects[i].key"];
    NSString *version = @"";
    if ([batch HasMember: @"objects[i].version_id"] == YES) {
        [textCompare Clear];
        [textCompare SetString: [batch StringOf: @"objects[i].version_id"]];
        BOOL sameText4 = [textCompare ContentsEqual: @"" caseSensitive: YES];
        if (([[batch JsonTypeOf: @"objects[i].version_id"] intValue] != 1) || (sameText4 == YES)) {
            NSLog(@"%@",@"version_id must be a nonempty string when present.");
            return;
        }

        version = [batch StringOf: @"objects[i].version_id"];
        [xml UpdateChildContent: @"Object[i]|VersionId" value: version];
    }

    [xml UpdateChildContent: @"Object[i]|Key" value: key];
    success = [identity UpdateString: @"key" value: key];
    if (success != YES) {
        NSLog(@"%@",@"Could not build saved state.");
        return;
    }

    success = [identity UpdateString: @"version" value: version];
    if (success != YES) {
        NSLog(@"%@",@"Could not build saved state.");
        return;
    }

    NSString *requestIdentity = [identity Emit];
    if ([requested Contains: requestIdentity] == YES) {
        NSLog(@"%@",@"Duplicate key/version in deletion batch.");
        return;
    }

    success = [requested AddInt: requestIdentity value: [NSNumber numberWithInt: 1]];
    if (success != YES) {
        NSLog(@"%@",@"Could not prepare the request.");
        return;
    }

    i = i + 1;
}

NSString *requestBody = [xml GetXml];
//  Explicit signing is used only for this fixed request so Content-MD5 survives.
//  Rest sends it; AuthAws must NOT also be configured on this Rest instance.
//  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: [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) {
    [textCompare Clear];
    [textCompare SetString: [credentials StringOf: @"session_token"]];
    BOOL sameText5 = [textCompare ContentsEqual: @"" caseSensitive: YES];
    if (sameText5 != YES) {
        [signedHeaders Append: @";x-amz-security-token"];
        [canonical Append: @"x-amz-security-token:"];
        [canonical Append: [credentials StringOf: @"session_token"]];
        [canonical Append: @"\n"];
        success = [rest AddHeader: @"x-amz-security-token" value: [credentials StringOf: @"session_token"]];
        if (success != YES) {
            NSLog(@"%@",@"Could not prepare the request.");
            return;
        }

    }

}

[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];
success = [rest AddHeader: @"Authorization" value: [authorization GetAsString]];
if (success != YES) {
    NSLog(@"%@",@"Could not prepare the request.");
    return;
}

success = [rest AddHeader: @"Content-MD5" value: contentMd5];
if (success != YES) {
    NSLog(@"%@",@"Could not prepare the request.");
    return;
}

success = [rest AddHeader: @"x-amz-content-sha256" value: payloadHash];
if (success != YES) {
    NSLog(@"%@",@"Could not prepare the request.");
    return;
}

success = [rest AddHeader: @"x-amz-date" value: amzDate];
if (success != YES) {
    NSLog(@"%@",@"Could not prepare the request.");
    return;
}

success = [rest AddQueryParam: @"delete" value: @""];
if (success != YES) {
    NSLog(@"%@",@"Could not prepare the request.");
    return;
}

NSString *responseBody = [rest FullRequestString: @"POST" uriPath: @"/" bodyText: requestBody];
if (rest.LastMethodSuccess != YES) {
    NSLog(@"%@",@"Request did not complete; inspect diagnostics privately.");
    return;
}

if ([rest.ResponseStatusCode intValue] != 200) {
    NSLog(@"%@%d",@"S3 HTTP status: ",[rest.ResponseStatusCode intValue]);
    success = [xml LoadXml: responseBody];
    [textCompare Clear];
    [textCompare SetString: xml.Tag];
    BOOL sameText6 = [textCompare ContentsEqual: @"Error" caseSensitive: YES];
    if ((success == YES) && (sameText6 == YES)) {
        NSLog(@"%@%@",@"S3 error code: ",[xml GetChildContent: @"Code"]);
    }

    //  Keep signed headers, credentials, URLs, and full diagnostics private.
    //  A timeout may leave a write's outcome uncertain. Check before retrying.
    return;
}

success = [xml LoadXml: responseBody];
if (success != YES) {
    NSLog(@"%@",@"Expected well-formed XML.");
    return;
}

[textCompare Clear];
[textCompare SetString: xml.Tag];
BOOL sameText7 = [textCompare ContentsEqual: @"DeleteResult" caseSensitive: YES];
if (sameText7 != YES) {
    NSLog(@"%@",@"Unexpected S3 response element; this is not a successful result.");
    return;
}

int deleted = [[xml NumChildrenHavingTag: @"Deleted"] intValue];
int failed = [[xml NumChildrenHavingTag: @"Error"] intValue];
if (deleted + failed != count) {
    NSLog(@"%@",@"Incomplete result: reconcile every requested object before retrying.");
    return;
}

CkoHashtable *received = [[CkoHashtable alloc] init];
int resultType = 0;
while ((resultType < 2)) {
    NSString *itemTag = @"Deleted";
    int resultCount = deleted;
    if (resultType == 1) {
        itemTag = @"Error";
        resultCount = failed;
    }

    int j = 0;
    while ((j < resultCount)) {
        xml.I = [NSNumber numberWithInt: j];
        CkoStringBuilder *itemPath = [[CkoStringBuilder alloc] init];
        success = [itemPath Append: itemTag];
        if (success != YES) {
            NSLog(@"%@",@"Could not build text.");
            return;
        }

        success = [itemPath Append: @"[i]"];
        if (success != YES) {
            NSLog(@"%@",@"Could not build text.");
            return;
        }

        CkoXml *item = [xml FindChild: [itemPath GetAsString]];
        if (xml.LastMethodSuccess != YES) {
            NSLog(@"%@",@"Missing deletion result entry.");
            return;
        }

        NSString *resultKey = [item GetChildContent: @"Key"];
        NSString *resultVersion = @"";
        if ([item HasChildWithTag: @"VersionId"] == YES) {
            resultVersion = [item GetChildContent: @"VersionId"];
        }

        success = [identity UpdateString: @"key" value: resultKey];
        if (success != YES) {
            NSLog(@"%@",@"Could not build saved state.");
            return;
        }

        success = [identity UpdateString: @"version" value: resultVersion];
        if (success != YES) {
            NSLog(@"%@",@"Could not build saved state.");
            return;
        }

        NSString *responseIdentity = [identity Emit];
        if (([requested Contains: responseIdentity] != YES) || ([received Contains: responseIdentity] == YES)) {
            NSLog(@"%@",@"Unexpected or duplicated deletion result; reconcile manually.");
            return;
        }

        success = [received AddInt: responseIdentity value: [NSNumber numberWithInt: 1]];
        if (success != YES) {
            NSLog(@"%@",@"Could not prepare the request.");
            return;
        }

        NSLog(@"%@%@%@",itemTag,@": ",resultKey);
        if (resultType == 1) {
            NSLog(@"%@%@",@"Error code: ",[item GetChildContent: @"Code"]);
        }

        j = j + 1;
    }

    resultType = resultType + 1;
}

if (failed > 0) {
    NSLog(@"%@",@"Batch has per-object failures. Do not retry successful entries.");
    return;
}

NSLog(@"%@",@"All requested deletions acknowledged.");