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

后端 未结 2 1656
失恋的感觉
失恋的感觉 2021-02-06 17:11

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

相关标签:
2条回答
  • 2021-02-06 17:25

    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 :)

    0 讨论(0)
  • 2021-02-06 17:45

    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 讨论(0)
提交回复
热议问题