开发者

How do I download a file from S3 to an iPhone application?

开发者 https://www.devze.com 2023-03-23 03:26 出处:网络
I am new to iPhone development.I am developing an iPhone application which needs to open files stored on Amazon\'s S3 service.开发者_开发技巧

I am new to iPhone development. I am developing an iPhone application which needs to open files stored on Amazon's S3 service.开发者_开发技巧

How do I download a file from S3 to my iPhone application? I have tried Amazon's SDK, but they don't seem to provide a means of downloading and saving a file. How do I go about obtaining a file's URL from S3 and saving it in my application?


I always use the ASIHttpRequest library to do this and it's quite simple, here's a sample code from their website:

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

You can't get easier than this :)


If you don't have the luxury of simplicity using ASI, and/or are stuck with AWSiOS SDK, it's not a lot different:

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

Then you can look at downloadResponse.body and downloadResponse.httpStatusCode, preferable in a delegate:

-(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 */
}   
0

精彩评论

暂无评论...
验证码 换一张
取 消