2

我不太确定如何使用 XCode 从 S3 下载数据。任何有关如何做到这一点的帮助将不胜感激。我尝试使用以下代码从 S3 访问图像,

AmazonCredentials *cred = [[Amazon alloc] initWithAccessKey:accessKey withSecretKey:secretAccessKey];
AmazonS3Client *s3 = [[AmazonS3Client alloc] initWithCredentials:cred];
S3GetObjectRequest *s3Request = [[S3GetObjectRequest alloc] initWithKey:urlPath      withBucket:bucket];
s3Request.delegate = self;
S3GetObjectResponse *s3Response = [s3 getObject:s3Request];

NSData*data = s3Response.body;
image = [UIImage imageWithData:data];

当我运行程序时,出现异常“EXC_BAD_ACCESS(代码 = 2,地址 = 0x0)”。我也不确定要在存储桶名称中包含什么。存储桶字符串应该只是“nameOfBucket”吗?或类似“topLevelFolder/nameOfBucket”的东西?另外,“urlPath”中具体应该包括什么?我认为我的异常可能与不正确的存储桶和 urlPath 名称有关。

编辑:我发现我们没有从 S3 获得任何数据,解决方案是删除“s3Request.delegate = self;”的行。

4

2 回答 2

2

这里有两种获取图像和检查图像是否存在的辅助方法

#import <AWSiOSSDK/S3/AmazonS3Client.h>

+(NSData *)getImage:(NSString *)imageID inFolder:(NSString *)folderName
{
// Initial the S3 Client.
//folderName = bucket name
AmazonS3Client *s3 = [[AmazonS3Client alloc] initWithAccessKey:ACCESS_KEY_ID withSecretKey:SECRET_KEY];
s3.timeout = 1000;

@try {


    NSString *pictName = [NSString stringWithFormat:@"%@%@", imageID, @".jpg"];

    S3GetObjectRequest *porr = [[S3GetObjectRequest alloc] initWithKey:pictName withBucket:folderName];
    // Get the image data from the specified s3 bucket and object.
    S3GetObjectResponse *response = [s3 getObject:porr]; 

    NSData *imageData = response.body;

    return imageData;

}
@catch (AmazonClientException *exception) {
    return nil;
}
}



+(BOOL)isImageExists:(NSString *)imageID inFolder:(NSString *)folderName
{
@try {

    AmazonS3Client *s3 = [[AmazonS3Client alloc] initWithAccessKey:ACCESS_KEY_ID withSecretKey:SECRET_KEY];
    NSString *pictName = [NSString stringWithFormat:@"%@%@", imageID, @".jpg"];
    NSLog(@"Start checking a full size image %@", imageID);

    S3GetObjectMetadataRequest *porr = [[S3GetObjectMetadataRequest alloc] initWithKey:pictName withBucket:folderName];

    S3GetObjectResponse *response = [s3 getObjectMetadata:porr];

    if(response)
    {
        return YES;
    }
}
@catch (AmazonServiceException *ex) {
    NSLog(@"AmazonServiceException in isImageExists %@", ex.description);
    return NO;
}
@catch (NSException *exception) {
    NSLog(@"NSException in isImageExists %@", exception.description);
    return NO;
}

return NO;
}
于 2013-05-29T05:55:11.587 回答
0

分配委托s3Request.delegate = self;会导致AmazonS3Client向委托方法 ( AmazonServiceRequestDelegate) 发送消息并抢占消息到S3GetObjectResponse

两种最常见的委托方法是:

-(void)request:(AmazonServiceRequest *)request didCompleteWithResponse:(AmazonServiceResponse *)response
-(void)request:(AmazonServiceRequest *)request didFailWithError:(NSError *)error
于 2013-10-23T17:20:16.360 回答