我刚接触iPhone开发。我正在开发一个需要打开Amazon S3服务中存储的文件的iPhone应用程序。
如何将S3上的文件下载到我的iPhone应用程序中?我尝试了Amazon的SDK,但它们似乎没有提供下载和保存文件的方法。我应该如何获取S3文件的URL并在我的应用程序中保存它?
我刚接触iPhone开发。我正在开发一个需要打开Amazon S3服务中存储的文件的iPhone应用程序。
如何将S3上的文件下载到我的iPhone应用程序中?我尝试了Amazon的SDK,但它们似乎没有提供下载和保存文件的方法。我应该如何获取S3文件的URL并在我的应用程序中保存它?
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]);
}
如果你没有使用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.body
和downloadResponse.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 */
}