Objective-C AWS S3: Copy S3 File to a Different Bucket

Back to Index

Demonstrates how to copy an S3 file from one bucket to another. The file can also be renamed if desired. (The file already exists in S3 in one bucket, and is copied without downloading/uploading to another S3 bucket.) This example copies from /chilkat.qa/starfish.jpg to /chilkat.ocean/starfishCopy.jpg

Documentation: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectCOPY.html

CURL Command

curl -X PUT https://chilkat.ocean.s3.us-west-2.amazonaws.com/starfishCopy.jpg \
    -H "x-amz-copy-source: /chilkat.qa/starfish.jpg"

Objective-C Example

#import <CkoRest.h>
#import <CkoAuthAws.h>
#import <CkoStringBuilder.h>
#import <CkoXml.h>
#import <NSString.h>

CkoRest *rest = [[CkoRest alloc] init];
BOOL success;

CkoAuthAws *authAws = [[CkoAuthAws alloc] init];
authAws.AccessKey = @"AWS_ACCESS_KEY";
authAws.SecretKey = @"AWS_SECRET_KEY";
authAws.Region = @"us-west-2";
authAws.ServiceName = @"s3";
[rest SetAuthAws: authAws];

//  URL: https://chilkat.ocean.s3.us-west-2.amazonaws.com/starfishCopy.jpg
BOOL bTls = YES;
int port = 443;
BOOL bAutoReconnect = YES;
success = [rest Connect: @"chilkat.ocean.s3.us-west-2.amazonaws.com" port: [NSNumber numberWithInt: port] tls: bTls autoReconnect: bAutoReconnect];
if (success != YES) {
    NSLog(@"%@%d",@"ConnectFailReason: ",[rest.ConnectFailReason intValue]);
    NSLog(@"%@",rest.LastErrorText);
    return;
}

[rest AddHeader: @"x-amz-copy-source" value: @"/chilkat.qa/starfish.jpg"];

CkoStringBuilder *sbResponseBody = [[CkoStringBuilder alloc] init];
success = [rest FullRequestNoBodySb: @"PUT" uriPath: @"/starfishCopy.jpg" sb: sbResponseBody];
if (success != YES) {
    NSLog(@"%@",rest.LastErrorText);
    return;
}

int respStatusCode = [rest.ResponseStatusCode intValue];
if (respStatusCode >= 400) {
    NSLog(@"%@%d",@"Response Status Code = ",respStatusCode);
    NSLog(@"%@",@"Response Header:");
    NSLog(@"%@",rest.ResponseHeader);
    NSLog(@"%@",@"Response Body:");
    NSLog(@"%@",[sbResponseBody GetAsString]);
    return;
}

CkoXml *xmlResponse = [[CkoXml alloc] init];
[xmlResponse LoadSb: sbResponseBody autoTrim: YES];

//  See the Online Tool for Generating XML Parse Code
NSString *CopyObjectResult_xmlns = 0;
NSString *tagPath = 0;
NSString *LastModified = 0;
NSString *ETag = 0;

CopyObjectResult_xmlns = [xmlResponse GetAttrValue: @"xmlns"];
LastModified = [xmlResponse GetChildContent: @"LastModified"];
ETag = [xmlResponse GetChildContent: @"ETag"];

Sample XML Response Body

<?xml version="1.0" encoding="UTF-8"?>
<CopyObjectResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <LastModified>2018-12-18T15:53:32.000Z</LastModified>
    <ETag>"2e9c59dbf2662367dc97dfdda85da048"</ETag>
</CopyObjectResult>