この問題を解決するために、私は Amazon の iOS SDK のサンプル コード (ここにある) から始めました。SDK zip では、目的のサンプル プロジェクトが にありますsamples/S3_Uploader
。
そのサンプル プロジェクトから、アップロードされた画像が公開されているプロジェクトに移行するには、適切な場所に 1 行を追加するだけです。
por.cannedACL = [S3CannedACL publicRead];
は画像のアップロードに使用されますpor
。S3PutObjectRequest
アップロード用の私のプロジェクトのコードは次のようになります (Amazon のサンプル コードとほぼ同じに見えます)。
NSString *uuid = @""; // Generate a UUID however you like, or use something else to name your image.
UIImage *image; // This is the UIImage you'd like to upload.
// This URL is not used in the example, but it points to the file
// to be uploaded.
NSString *url = [NSString pathWithComponents:@[ @"https://s3.amazonaws.com/", AWS_PICTURE_BUCKET, uuid ]];
// Convert the image to JPEG data. Use UIImagePNGRepresentation for pngs
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
// Create the S3 Client.
AmazonS3Client *s3 = [[AmazonS3Client alloc] initWithAccessKey:AWS_ACCESS_KEY_ID withSecretKey:AWS_SECRET_KEY];
@try {
// Create the picture bucket.
[s3 createBucket:[[S3CreateBucketRequest alloc] initWithName:AWS_PICTURE_BUCKET]];
// Upload image data. Remember to set the content type.
S3PutObjectRequest *por = [[S3PutObjectRequest alloc] initWithKey:uuid inBucket:AWS_PICTURE_BUCKET];
por.contentType = @"image/jpeg"; // use "image/png" here if you are uploading a png
por.cannedACL = [S3CannedACL publicRead];
por.data = imageData;
por.delegate = self; // Don't need this line if you don't care about hearing a response.
// Put the image data into the specified s3 bucket and object.
[s3 putObject:por];
}
@catch (AmazonClientException *exception) {
NSLog(@"exception");
}
AWS_ACCESS_KEY_ID
とAWS_SECRET_KEY
はもちろん、AWS 認証情報でありAWS_PICTURE_BUCKET
、画像バケットです。