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

S3: Download a File Safely

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.

Downloads the exact key to an unused temporary path, requires HTTP 200, compares the local byte count with Content-Length, and renames only after success. Create the output directory first. Interrupted or failed downloads are not promoted to the final path. This is not a resumable download and does not independently verify an S3 checksum; ETag must not be assumed to be MD5.

Requires s3:GetObject, or s3:GetObjectVersion for a specified version, plus applicable KMS permissions. Archived S3 Glacier Flexible Retrieval or Deep Archive objects must be restored before reading; a restoration request does not immediately make them downloadable. Use the original key without adding a leading slash.

AWS reference

Chilkat Objective-C Downloads

Objective-C
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <CkoHttp.h>
#import <NSString.h>
#import <CkoFileAccess.h>
#import <CkoMime.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";
//  A leading slash is part of a key. Do not add one to imitate a file path.
NSString *objectName = @"images/seahorse.jpg";

//  Start with the original key. Encode once and retain '/' path separators.
//  This also protects a literal "%2F" from being interpreted as a slash.
CkoStringBuilder *keyPath = [[CkoStringBuilder alloc] init];
[keyPath Append: [http UrlEncode: objectName]];
int slashCount = [[keyPath ReplaceNoCase: @"%2f" replacement: @"/"] intValue];
NSString *encodedKey = [keyPath GetAsString];
CkoFileAccess *files = [[CkoFileAccess alloc] init];
NSString *finalPath = @"qa_output/seahorse.jpg";
NSString *partialPath = @"qa_output/seahorse.jpg.part";
if (([files FileExists: finalPath] == YES) || ([files FileExists: partialPath] == YES)) {
    NSLog(@"%@",@"Choose unused output paths before downloading.");
    return;
}

success = [http S3_DownloadFile: bucketName objectName: encodedKey localFilePath: partialPath];
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 ([http.LastStatus intValue] != 200) {
    NSLog(@"%@%d",@"Unexpected HTTP status: ",[http.LastStatus intValue]);
    return;
}

CkoMime *headers = [[CkoMime alloc] init];
success = [headers LoadMime: http.LastResponseHeader];
if (success != YES) {
    NSLog(@"%@",@"Could not parse download headers; keep the .part file.");
    return;
}

NSString *expectedSize = [headers GetHeaderField: @"Content-Length"];
[stringCompare SetString: expectedSize];
BOOL stringMatch4 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((headers.LastMethodSuccess != YES) || (stringMatch4 == YES)) {
    NSLog(@"%@",@"Missing Content-Length; keep the .part file.");
    return;
}

NSString *actualSize = [files FileSizeStr: partialPath];
[stringCompare SetString: actualSize];
BOOL stringMatch5 = [stringCompare ContentsEqual: expectedSize caseSensitive: YES];
if ((files.LastMethodSuccess != YES) || (stringMatch5 != YES)) {
    NSLog(@"%@",@"Downloaded byte count mismatch; keep the .part file.");
    return;
}

success = [files FileRename: partialPath newPath: finalPath];
if (success != YES) {
    NSLog(@"%@",@"Downloaded file remains at the .part path; rename failed.");
    return;
}

NSLog(@"%@",@"File download succeeded; byte count verified.");