Friday, 3 April 2015

Amazon AWS S3 Integration in iOS App



Sometime uploading the large files to the local server and then upload it to the Amazon S3 server takes time. But now it is a easy task to upload the large files directly to the Amazon S3 server and keeping track of the uploaded files on your local server.

This blog provides the easy steps to integrate and upload the data on the S3 server from the iOS App.



Sign up to get the Amazon S3 – You should have AWS account to use the Amazon S3. If not, you can create this by using the following link. http://aws.amazon.com/s3

Creating a bucket – Once you have created a account and get the AWS credentials then you need to create the bucket. Bucket is the storage where you will store your files. You can create a bucket by using the following link.

Integrating the AWS iOS SDK –

1) Download the SDK from https://aws.amazon.com/mobile/sdk/ .

2) Add the followings framework located in the third party SDK.
  • Bolts.framework (If your application uses the Facebook SDK, you won't need this framework, as it's already included with the Facebook SDK.)
  • FMDB.framework
  • SystemConfiguration.framework
  • Mantle.framework
  • Reachability.framework
  • TMCache.framework
  • UICKeyChainStore.framework
  • XMLDictionary.framework


3) Drag and drop the following JSON files, located in the service-definitions directory, into your project.
  • cognito-sync-2014-06-30.json
  • dynamodb-2012-08-10.json
  • ec2-2014-06-15.json
  • elasticloadbalancing-2012-06-01.json
  • email-2010-12-01.json
  • kinesis-2013-12-02.json
  • mobileanalytics-2014-06-30.json
  • monitoring-2010-08-01.json
  • s3-2006-03-01.json
  • sdb-2009-04-15.json
  • sns-2010-03-31.json
  • sqs-2012-11-05.json
  • sts-2011-06-15.json
  • autoscaling-2011-01-01.json

4) Add the following Libraries.
  • libsqlite3.dylib
  • libz.dylib


Creating Amazon Cognito Identity – Next step is to create the Amazon Cognito ID that will be used in uploading the files. You can create it from the following link -http://docs.aws.amazon.com/mobile/sdkforios/developerguide/cognito-auth.html


Uploading a File on Amazon S3 Server -

1) Import the following header file in your class.

                #import <AWSiOSSDKv2/AWSCore.h>
                #import <AWSiOSSDKv2/AWSS3TransferManager.h>
                #import <AWSiOSSDKv2/AWSCredentialsProvider.h>
                #import <AWSiOSSDKv2/S3.h>

2) Initialize the configuration in App Delegate's application:didFinishLaunchingWithOptions.

AWSCognitoCredentialsProvider *credentialsProvider = [AWSCognitoCredentialsProvider
credentialsWithRegionType:AWSRegionUSEast1
identityPoolId:PLACE_YOUR_COGNITO_POOL_ID_HERE];

AWSServiceConfiguration *configuration = [AWSServiceConfiguration configurationWithRegion:AWSRegionUSWest2 credentialsProvider:credentialsProvider];
AWSServiceManager.defaultServiceManager.defaultServiceConfiguration = configuration;


Note-  *Place the specified region type where your bucket is located. I have used               AWSRegionUSEast1.
           *Provide your region name in 'AWSCognitoCredentialsProvider' where your server has located.   
           *Provide your region name in 'AWSServiceConfiguration' where your bucket has located.


3) Call the AWS Service in your class.

AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];
AWSS3TransferManagerUploadRequest *uploadRequest = [[AWSS3TransferManagerUploadRequest alloc]init];
uploadRequest.bucket = PLACE_YOUR_BUCKET_NAME_HERE;
uploadRequest.key = NAME_OF_THE_FILE_BY_WHICH_IT_WILL_BE_SAVED; //Use below function to get unique file name
uploadRequest.body = [NSURL fileURLWithPath:LOCAL_FILEPATH_OF_FILE_WHICH_WILL_UPLOAD];
BFTask *task = [transferManager upload:uploadRequest];
[task continueWithBlock:^id(BFTask *task)
{
            //Handle the response here
}];



Note– If you want to access the image through URL then be sure that your bucket is set to public permission otherwise you will get the authentication error.


Sample Code:


/**
* To upload the file on S3 Server.
*
* @param bucketName bucket on which file to be uploaded
* @param filePath path of the file to be uploaded
* @param fileName fileName by which it will be saved on server
* @param responseBlock returns the response block containing result.If upload is success then returns TRUE otherwise returns FALSE
*/
+ (void)uploadFileToS3Bucket:(NSString*)bucketName filePath:(NSString*)filePath fileName:(NSString*)fileName completionHandler:(void(^)(BOOL result))responseBlock
{
          AWSS3TransferManager *transferManager = [AWSS3TransferManager   defaultS3TransferManager];
          AWSS3TransferManagerUploadRequest *uploadRequest =              [[AWSS3TransferManagerUploadRequest alloc]init];
          uploadRequest.bucket = bucketName;
          uploadRequest.key = fileName;
          uploadRequest.body = [NSURL fileURLWithPath:filePath];
          BFTask *task = [transferManager upload:uploadRequest];
          [task continueWithBlock:^id(BFTask *task)
         {
               if (task.error)
              {
                    if ([task.error.domain isEqualToString:AWSS3TransferManagerErrorDomain])
                   {
                              switch (task.error.code)
                            {
                                   case AWSS3TransferManagerErrorCancelled:
                                           responseBlock(FALSE);
                                            break;
                                    case AWSS3TransferManagerErrorPaused:
                                            responseBlock(FALSE);
                                            break;
                                     default:
                                             responseBlock(FALSE);
                                             break;
                             }
                    } else
                   {
                               NSLog(@"Upload failed: [%@]", task.error);
                               responseBlock(FALSE);
                     }
              }
              if (task.result)
             {
                     responseBlock(TRUE);
              }
              return nil;
    }];
}


/**
* Getting unique filename
* @return returns the unique filename created
*/
+ (NSString*)getUniqueFileName
{
        NSString *fileName = [[[NSProcessInfo processInfo] globallyUniqueString]        stringByAppendingString:@".png"];
        return fileName;
}

5 comments:

  1. Excellent Work. Really helpful :)

    ReplyDelete



  2. I like the article on the topic due to this reason it is seen that other readers are showing their interest by commenting on it.


    Google App Integration Chennai

    ReplyDelete
  3. I get a lot of great information here and this is what I am searching for. Thank you for your sharing. I have bookmark this page for my future reference.view aws jobs in hyderabad

    ReplyDelete