amazon s3 iphone sdk 下载图片

Posted

技术标签:

【中文标题】amazon s3 iphone sdk 下载图片【英文标题】:amazon s3 iphone sdk downloading images 【发布时间】:2012-07-31 22:05:55 【问题描述】:

在我的一生中,我无法弄清楚如何在我的 ios 项目中实现亚马逊的 sdk,而且我似乎找不到太多关于我正在尝试做什么的文档......希望你能提供帮助!

我想非常简单地从我的 Amazon S3 帐户下载文件并将它们本地存储在 iPhone 上...我可以通过 http 地址访问图像来做到这一点,但这并不能像我一样保护图像更喜欢。

根据我的阅读,我应该这样做:

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];

我显然在 getObjectResponse、getObject 代码上做错了,但我不知道正确的语法...任何帮助将不胜感激!

这是日志: 2012-08-02 17:12:33.856 收藏大师版[13176:4e07] 请求对象: 2012-08-02 17:12:34.044 Collection Master Edition[13176:4e07] * 由于未捕获的异常“AmazonServiceException”而终止应用程序,原因:“(null)”

也许我还应该提到我可以使用以下代码获取存储桶列表内容

 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

        

谢谢! 扎克

【问题讨论】:

您可能需要重新考虑这样做,而是在您的 iOS 应用程序和 S3 之间添加一个 Web 服务层。否则,您将需要将您的 AWS 凭证放入应用程序本身。因此,如果有人破解了您的应用程序,他们可以完全访问您的 S3 存储(以及该密钥可用的任何其他 Amazon 服务)。 我已经考虑过了,并且已经设置了 TVM Web 服务层...但是我无法通过第一步开始测试 TVM 步骤...我想如果我可以使上述代码正常工作,我可以继续前进(并提出更多问题!)以使 TVM 正常工作-想法?除非你对整个事情有建议! 嘿,你解决了这个问题吗?我在这里面临同样的问题。 对于遇到同样问题的任何人,这篇文章对我有帮助:***.com/questions/18318487/… 【参考方案1】:

从我在这里看到的情况来看,您可能会遇到两个问题之一。我第一次开始使用 AWS 时遇到了类似的问题。首先确保您的存储桶名称全部为小写字母。您应该通过将其放入 @try - @catch 块并记录错误来检查为什么会发生这种情况,这在解决您的问题时提供了非常详细的信息。

    -(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);


 

【讨论】:

【参考方案2】:

问题可能是与您的密钥对关联的权限。我的建议是去你的IAM on your Management Console 并创建一个具有你想要的适当 S3 权限的新组,在这种情况下几乎所有这些权限,除了一些你不需要的更多管理的东西(所以主要只是 POST,GET权限)。然后在该组中创建一个用户并使用该密钥对进行测试。这可能会让事情变得清晰,因为这是我认为对我有用的过程。貌似列表权限比较低,但是POST和GET需要不同的权限。

【讨论】:

【参考方案3】:

可能是允许的,但可能会帮助某些人。这是在amazone-s3中上传图片的代码

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

#define PICTURE_BUCKET @"桶名" #define PICTURE_NAME @"任何单词" #define CREDENTIALS_ERROR_TITLE @"缺少凭据" #define CREDENTIALS_ERROR_MESSAGE @"AWS 凭证配置不正确。请查看 README 文件。"

@interface 常量:NSObject

+(NSString *)pictureBucket;

@结束

在常量.m中

#import "Constant.h"

@implementation 常量 +(NSString *)图片桶 return [[NSString stringWithFormat:@"%@-%@", PICTURE_BUCKET, ACCESS_KEY_ID] lowercaseString];

@end

在 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;

在 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 credentials into source code.
    // DO NOT EMBED YOUR CREDENTIALS IN PRODUCTION APPS.
    // We offer two solutions for getting credentials 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:(NSString *)message withTitle:(NSString *)title UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title 消息:消息 代表:无 取消按钮标题:@“确定” 其他按钮标题:无]; alertView.delegate=self; [警报视图显示]; - (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 sharedApplication] 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 sharedApplication] setNetworkActivityIndicatorVisible:NO];
  

 -(void)request:(AmazonServiceRequest *)request didFailWithError:(NSError *)error
  
NSLog(@"Error: %@", error);
[self showAlertMessage:error.description withTitle:@"Upload Error"];

[[UIApplication sharedApplication] 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 sharedApplication] 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

【讨论】:

以上是关于amazon s3 iphone sdk 下载图片的主要内容,如果未能解决你的问题,请参考以下文章

Amazon S3 iOS SDK 照片上传有时会出错 - SignatureDoesNotMatch

如何使用AWS SDK从S3下载对象--RESTful。

如何使用AWS SDK从S3下载对象--RESTful。

AWS S3 IOS中的混乱sdk?

waitUntilObjectExists() Amazon S3 PHP SDK 方法,它究竟是如何工作的?

使用 amazon sdk 和存储桶策略从 ios 应用程序将图像上传到 amazon s3