amazon s3 iphone sdk download imágenes

No puedo, para mi vida, imaginar cómo implementar el SDK de Amazon en mi proyecto de iOS, y no puedo encontrar mucha documentation sobre lo que estoy tratando de hacer … ¡aquí espero que puedas ayudar!

Quiero, simplemente, download files de mi count de Amazon S3 y almacenarlos localmente en el iPhone … Puedo hacerlo accediendo a las imágenes a través de la dirección http, pero eso no protege las imágenes como preferiría.

Por lo que he leído, debería estar haciendo algo como esto:

AmazonS3Client *s3Client = [[AmazonS3Client alloc] initWithAccessKey:@"mykey" withSecretKey:@"mysecretkey"]; S3GetObjectRequest *requestedObject = [[S3GetObjectRequest alloc] initWithKey:bucketPath withBucket:@"mybucket"]; NSLog(@"requestedobject:%@", requestedObject - I get the log here); S3GetObjectResponse *getObjectResponse = [s3Client getObject:requestedObject]; NSLog(@"requestedobject2:%@", getObjectResponse - it crashes before this happens); NSData *myData2; myData2 = getObjectResponse.body; [myData2 writeToFile:bucketPath atomically:YES]; 

Estoy claramente haciendo algo mal con el código getObjectResponse, getObject, pero no puedo encontrar la syntax correcta … ¡cualquier ayuda sería apreciada!

Aquí está el logging: 2012-08-02 17: 12: 33.856 Colección Edición Maestra [13176: 4e07] object solicitado: 08-08-2012 17: 12: 34.044 Colección Edición Maestra [13176: 4e07] * Aplicación de finalización debido a una exception no detectada 'AmazonServiceException', motivo: '(nulo)'

Tal vez debería mencionar que PUEDO get los contenidos de la list de cubo con el siguiente código

  S3ListObjectsRequest *listObjectRequest = [[S3ListObjectsRequest alloc] initWithName:@"my bucket"]; S3ListObjectsResponse *listObjectResponse = [s3Client listObjects:listObjectRequest]; S3ListObjectsResult *listObjectsResults = listObjectResponse.listObjectsResult; for (S3ObjectSummary *objectSummary in listObjectsResults.objectSummaries) { NSLog(@"Bucket Contents:%@" ,[objectSummary key]); // This returns the contents of the bucket } 

¡Gracias! Zack

Por lo que veo aquí, puede tener uno de los dos problemas. Tuve problemas similares cuando empecé a usar AWS por primera vez. Primero asegúrate de que el nombre del cubo esté en letras minúsculas. Debe comprobar para ver por qué sucede esto puffing it en un bloque @try – @catch y registrar los errores, que proporcionan gran detalle al resolver su problema.

  -(UIImage *)getImageFromS3{ @try{ AmazonS3Client *_s3Client = [[AmazonS3Client alloc]initWithAccessKey:ACCESS_KEY withSecretKey:SECRET_KEY]; S3GetObjectRequest *getObjectRequest = [[S3GetObjectRequest alloc]initWithKey:imageKey withBucket:pictureBucket]; S3GetObjectResponse *response = [_s3Client getObject:getObjectRequest]; if (response.error == nil) { if (response.body != nil) { UIImage *someImage = [UIImage imageWithData:reponse.body]; return someImage; } else{ NSLog(@"There was no value in the response body"); return nil; } } else if (response.error != nil) { NSLog(@"There was an error in the response while getting image: %@",response.error.description); } } @catch (NSException *exception) { NSLog(@"There was an exception when connecting to s3: %@",exception.description); } } 

Lo que podría ser el problema son los permissions asociados con su par de keys. Lo que le aconsejo es ir a su IAM en su Management Console y crear un nuevo grupo con los permissions S3 adecuados que desee, en este caso casi todos excepto algunas de las cosas más administrativas que no necesitará (por lo tanto, solo POST , OBTENER permissions). Luego, cree un usuario dentro de ese grupo y use ese par de keys para probar. Esto puede aclarar las cosas, ya que ese es el process que creo que funcionó para mí. Parece que el permiso de la list es bastante bajo nivel, sin embargo, POST y GET requieren diferentes permissions.

Puede ser que sea permitido, pero podría ayudar a alguien. Aquí está el código para cargar la image en amazone-s3

 constant.h #import <Foundation/Foundation.h> #define SECRET_KEY @"your secret kry" #define ACCESS_KEY_ID @"your access id" 

#define PICTURE_BUCKET @ "nombre del depósito" #define PICTURE_NAME @ "cualquier palabra" #define CREDENTIALS_ERROR_TITLE @ "Cnetworkingenciales perdidas" #define CREDENTIALS_ERROR_MESSAGE @ "Las cnetworkingenciales de AWS no están configuradas correctamente. Revise el file README".

@interface Constante: NSObject

+ (NSString *) pictureBucket;

@fin

En constant.m

#import "Constant.h"

@implementation Constant + (NSString *) pictureBucket {return [[NSString stringWithFormat: @ "% @ -% @", PICTURE_BUCKET, ACCESS_KEY_ID] lowercaseString]; }

 @end 

En UploadViewController.h

  typedef enum { GrandCentralDispatch, Delegate, BackgroundThread } UploadType; @interface UploadPhotoViewController : UIViewController<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UINavigationControllerDelegate, AmazonServiceRequestDelegate> { UploadType _uploadType; } @property (strong, nonatomic) IBOutlet UIButton *buttonSelectPhoto; @property (nonatomic, retain) AmazonS3Client *s3; 

En UploadViewController.m

  #import "UploadPhotoViewController.h" #import <AWSRuntime/AWSRuntime.h> #import "Constant.h" @interface UploadPhotoViewController () @end @implementation UploadPhotoViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. #ifdef DEBUG [AmazonLogger verboseLogging]; #else [AmazonLogger turnLoggingOff]; #endif [AmazonErrorHandler shouldNotThrowExceptions]; if(![ACCESS_KEY_ID isEqualToString:@"CHANGE ME"] && self.s3 == nil) { // Initial the S3 Client. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // This sample App is for demonstration purposes only. // It is not secure to embed your cnetworkingentials into source code. // DO NOT EMBED YOUR CREDENTIALS IN PRODUCTION APPS. // We offer two solutions for getting cnetworkingentials to your mobile App. // Please read the following article to learn about Token Vending Machine: // * http://aws.amazon.com/articles/Mobile/4611615499399490 // Or consider using web identity federation: // * http://aws.amazon.com/articles/Mobile/4617974389850313 //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! self.s3 = [[AmazonS3Client alloc] initWithAccessKey:ACCESS_KEY_ID withSecretKey:SECRET_KEY] ; self.s3.endpoint = [AmazonEndpoints s3Endpoint:US_WEST_2]; // Create the picture bucket. S3CreateBucketRequest *createBucketRequest = [[S3CreateBucketRequest alloc] initWithName:[Constant pictureBucket] andRegion:[S3Region USWest2]]; S3CreateBucketResponse *createBucketResponse = [self.s3 createBucket:createBucketRequest]; if(createBucketResponse.error != nil) { NSLog(@"Error: %@", createBucketResponse.error); } } } -(void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; if ([ACCESS_KEY_ID isEqualToString:@"CHANGE ME"]) { [self showAlertMessage:CREDENTIALS_ERROR_MESSAGE withTitle:CREDENTIALS_ERROR_TITLE]; } 

} – (void) showAlertMessage: post (NSString *) withTitle: (NSString *) title {UIAlertView * alertView = [[UIAlertView alloc] initWithTitle: título post: delegado de post: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil]; alertView.delegate = self; [alertView show]; } – (void) alertView: (UIAlertView *) alertView clickedButtonAtIndex: (NSInteger) buttonIndex {

 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue, ^{ // Set the content type so that the browser will treat the URL as an image. S3ResponseHeaderOverrides *override = [[S3ResponseHeaderOverrides alloc] init]; override.contentType = @"image/jpeg"; // Request a pre-signed URL to picture that has been uplaoded. S3GetPreSignedURLRequest *gpsur = [[S3GetPreSignedURLRequest alloc] init]; gpsur.key = PICTURE_NAME; gpsur.bucket = [Constant pictureBucket]; gpsur.expires = [NSDate dateWithTimeIntervalSinceNow:(NSTimeInterval) 3600]; // Added an hour's worth of seconds to the current time. gpsur.responseHeaderOverrides = override; // Get the URL NSError *error = nil; NSURL *url = [self.s3 getPreSignedURL:gpsur error:&error]; if(url == nil) { if(error != nil) { dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"Error: %@", error); [self showAlertMessage:[error.userInfo objectForKey:@"message"] withTitle:@"Browser Error"]; }); } } else { /*dispatch_async(dispatch_get_main_queue(), ^{ // Display the URL in Safari [[UIApplication shanetworkingApplication] openURL:url]; });*/ }NSLog(@"url is %@",url); }); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (IBAction)buttonTakePhoto:(id)sender { UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = self; picker.allowsEditing = YES; picker.sourceType = UIImagePickerControllerSourceTypeCamera; [self presentViewController:picker animated:YES completion:NULL]; } - (IBAction)buttonSelectPhoto:(id)sender { [self showImagePicker:Delegate]; } - (void)showImagePicker:(UploadType)uploadType { UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init] ; imagePicker.delegate = self; _uploadType = uploadType; [self presentViewController:imagePicker animated:YES completion:NULL]; } - (void)processDelegateUpload:(NSData *)imageData { // Upload image data. Remember to set the content type. S3PutObjectRequest *por = [[S3PutObjectRequest alloc] initWithKey:PICTURE_NAME inBucket:[Constant pictureBucket]]; por.contentType = @"image/jpeg"; por.data = imageData; por.delegate = self; // Put the image data into the specified s3 bucket and object. [self.s3 putObject:por]; } -(void)request:(AmazonServiceRequest *)request didCompleteWithResponse:(AmazonServiceResponse *)response { [self showAlertMessage:@"The image was successfully uploaded." withTitle:@"Upload Completed"]; [[UIApplication shanetworkingApplication] setNetworkActivityIndicatorVisible:NO]; } -(void)request:(AmazonServiceRequest *)request didFailWithError:(NSError *)error { NSLog(@"Error: %@", error); [self showAlertMessage:error.description withTitle:@"Upload Error"]; [[UIApplication shanetworkingApplication] setNetworkActivityIndicatorVisible:NO]; } #pragma mark - UIImagePickerControllerDelegate methods -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { // Get the selected image. UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; // Convert the image to JPEG data. NSData *imageData = UIImageJPEGRepresentation(image, 1.0); if(_uploadType == Delegate) { [self processDelegateUpload:imageData]; } [[UIApplication shanetworkingApplication] setNetworkActivityIndicatorVisible:YES]; [picker dismissViewControllerAnimated:YES completion:NULL]; } -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [picker dismissViewControllerAnimated:YES completion:NULL]; } - (IBAction)buttonBack:(id)sender { [self.navigationController popViewControllerAnimated:YES]; } @end