AWS S3 file download with progress status using Amazon SDK

08 / Jul / 2015 by Ashu Baweja 0 comments

In the first part you learned how to setup Amazon SDK and upload file on S3. In this part, you will learn how to download file with progress status from Amazon S3.

Getting Started :

  • Import following headers into your viewController:

[code language=”objc”]
#import <AWSiOSSDKv2/AWSCore.h>
[/code]

  • To use the S3 TransferManager, we first need to create a TransferManager client ( AWSS3TransferManager class is our entry point to the high-level S3 API ):

[code language=”objc”]
AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];
[/code]

Download File:

To download a file from a bucket, we have to construct the request using AWSS3TransferManagerDownloadRequest and then pass this request to the download method of client. First you need to create an NSURL that we’ll use for a download location.

  • Construct the NSURL for the download location

[code language=”objc”]
NSString *downloadingFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"name of file with which you want to save example :image.jpg"];
NSURL *downloadingFileURL = [NSURL fileURLWithPath:downloadingFilePath];
[/code]

  • Construct the download request

[code language=”objc”]
AWSS3TransferManagerDownloadRequest *downloadRequest = [AWSS3TransferManagerDownloadRequest new];
downloadRequest.bucket = @"your S3 bucket name";
downloadRequest.key = @"key with which you have uploaded the file";
downloadRequest.downloadingFileURL = downloadingFileURL;
[/code]

  • Now pass the download request to the download: method of the TransferManager client.

[code language=”objc”]
[[transferManager download : downloadRequest] continueWithExecutor : [BFExecutor mainThreadExecutor] withBlock: ^id(BFTask*task) {
if (task.error){

NSLog(@"Error: %@", task.error);
}
else{
// File downloaded successfully.
}

return nil;
}];
[/code]

Track Progress :

Using the uploadProgress and downloadProgress blocks, you can track the progress of object transfers.

Upload Progress:

[code language=”objc”]
uploadRequest.uploadProgress = ^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend){
dispatch_async(dispatch_get_main_queue(), ^{

// upload progress
});
[/code]

Download Progress:

[code language=”objc”]
downloadRequest.downloadProgress = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite){
dispatch_async(dispatch_get_main_queue(), ^{

// download progress
});
[/code]

Run your app and check out its working fine. Congratulations! your file has downloaded from Amazon S3 Bucket.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *