如何将文件从S3下载到iPhone应用程序?

时间:2011-07-26 11:34:53

标签: iphone objective-c ios amazon-s3

我是iPhone开发的新手。我正在开发一个需要打开存储在亚马逊S3服务上的文件的iPhone应用程序。

如何将文件从S3下载到我的iPhone应用程序?我尝试过亚马逊的SDK,但它们似乎没有提供下载和保存文件的方法。如何从S3获取文件的URL并将其保存在我的应用程序中?

2 个答案:

答案 0 :(得分:3)

我总是使用ASIHttpRequest library来做这件事,这很简单,这是他们网站的示例代码:

NSString *secretAccessKey = @"my-secret-access-key";
NSString *accessKey = @"my-access-key";
NSString *bucket = @"my-bucket";
NSString *path = @"path/to/the/object";

ASIS3ObjectRequest *request = [ASIS3ObjectRequest requestWithBucket:bucket key:path];
[request setSecretAccessKey:secretAccessKey];
[request setAccessKey:accessKey];
[request startSynchronous];
if (![request error]) {
  NSData *data = [request responseData];
} else {
  NSLog(@"%@",[[request error] localizedDescription]);
}

你不能比这更容易:)

答案 1 :(得分:3)

如果您没有使用ASI的简单性和/或使用AWSiOS SDK,那么它并没有太大区别:

/* borrowed from Maurício Linhares's answer */
NSString *secretAccessKey = @"my-secret-access-key";
NSString *accessKey = @"my-access-key";
NSString *bucket = @"my-bucket";
NSString *path = @"path/to/the/object";
/********************************************/

AmazonCredentials *credentials = [[AmazonCredentials alloc] initWithAccessKey: accessKey withSecretKey: secretAccessKey];
AmazonS3Client *connection = [[AmazonS3Client alloc] initWithCredentials: credentials];

S3GetObjectRequest *downloadRequest = [[[S3GetObjectRequest alloc] initWithKey:path withBucket: bucket] autorelease];
[downloadRequest setDelegate: self]; /* only needed for delegate (see below) */
S3GetObjectResponse *downloadResponse = [self.awsConnection getObject: downloadRequest];

然后,您可以查看downloadResponse.bodydownloadResponse.httpStatusCode,最好是代表:

-(void)request: (S3Request *)request didCompleteWithResponse: (S3Response *) response {
    NSLog(@"Download finished (%d)",response.httpStatusCode);
    /* do something with response.body and response.httpStatusCode */
    /* if you have multiple requests, you can check request arg */
}