Menu
AWS Mobile
Developer Guide

How to Integrate Your Existing Bucket

Just Getting Started?

Use streamlined steps to install the SDK and integrate Amazon S3.

Or, use the contents of this page if your app will integrate existing AWS services.

The following steps include:

  • Set up short-lived credentials for accessing your AWS resources using a Cognito Identity Pool.

  • Create an AWS Mobile configuration file that ties your app code to your bucket.

Set Up Your Backend

If you already have a Cognito Identity Pool and have its unauthenticated IAM role set up with read/write permissions on the S3 bucket, you can skip to Get Your Bucket Name and ID.

Create or Import the Amazon Cognito Identity Pool

  1. Go to Amazon Cognito Console and choose Manage Federated Identities.

  2. Choose Create new Identity pool on the top left of the console.

  3. Type a name for the Identity pool, select Enable access to unauthenticated identities under the Unauthenticated Identities section, and then choose Create pool on the bottom right.

  4. Expand the View Details section to see the two roles that are to be created to enable access to your bucket. Copy and keep the Unauthenticated role name, in the form of Cognito_<IdentityPoolName>Unauth_Role, for use in a following configuration step. Choose Allow on the bottom right.

  5. In the code snippet labeled Get AWSCredentials displayed by the console, copy the Identity Pool ID and the Region for use in a following configuration step.

Set up the required Amazon IAM permissions

  1. Go to Amazon IAM Console and choose Roles.

  2. Choose the unauthenticated role whose name you copied in a previous step.

  3. Choose Attach Policy, select the AmazonS3FullAccess policy, and then choose Attach Policy to attach it to the role.

Note

The AmazonS3FullAccess policy will grant users in the identity pool full access to all buckets and operations in Amazon S3. In a real app, you should restrict users to only have access to the specific resources they need. For more information, see Amazon S3 Security Considerations.

Get Your Bucket Name and ID

  1. Go to Amazon S3 Console and select the bucket you want to integrate.

  2. Copy and keep the bucket name value from the breadcrumb at the top of the console, for use in a following step.

  3. Copy and keep the bucket's region, for use in a following step.

Connect to Your Backend

Create the awsconfiguration.json file

  1. Create a file with name awsconfiguration.json with the following contents:

    { "Version": "1.0", "CredentialsProvider": { "CognitoIdentity": { "Default": { "PoolId": "COGNITO-IDENTITY-POOL-ID", "Region": "COGNITO-IDENTITY-POOL-REGION" } } }, "IdentityManager" : { "Default" : { } }, "S3TransferUtility": { "Default": { "Bucket": "S3-BUCKET-NAME", "Region": "S3-REGION" } } }
  2. Make the following changes to the configuration file.

    • Replace the COGNITO-IDENTITY-POOL-ID with the identity pool ID.

    • Replace the COGNITO-IDENTITY-POOL-REGION with the region the identity pool was created in.

    • Replace the S3-BUCKET-NAME with the name of your bucket.

    • Replace the S3-REGION with the region your bucket was created in.

Add the awsconfiguration.json file to your app

Android - JavaAndroid - KotliniOS - Swift
Android - Java

In the Android Studio Project Navigator, right-click your app's res folder, and then choose New > Directory. Type raw as the directory name and then choose OK.


                        Image of creating a raw directory in Android Studio.

Drag the awsconfiguration.json you created into the res/raw folder. Android gives a resource ID to any arbitrary file placed in this folder, making it easy to reference in the app.

Android - Kotlin

In the Android Studio Project Navigator, right-click your app's res folder, and then choose New > Directory. Type raw as the directory name and then choose OK.


                        Image of creating a raw directory in Android Studio.

Drag the awsconfiguration.json you created into the res/raw folder. Android gives a resource ID to any arbitrary file placed in this folder, making it easy to reference in the app.

iOS - Swift

Drag the awsconfiguration.json into the Xcode Project Navigator folder containing Info.plist. Choose Copy items and Create groups in the options dialog.

Add the SDK to your App

Android - JavaAndroid - KotliniOS - Swift
Android - Java

Set up AWS Mobile SDK components as follows:

  1. Add the following to app/build.gradle:

    dependencies { implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.6.+@aar') { transitive = true } implementation 'com.amazonaws:aws-android-sdk-s3:2.6.+' implementation 'com.amazonaws:aws-android-sdk-cognito:2.6.+' }

    Perform a Gradle Sync to download the AWS Mobile SDK components into your app

  2. Add the following to AndroidManifest.xml:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application ... > <!- . . . -> <service android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService" android:enabled="true" /> <!- . . . -> </application>
  3. For each Activity where you make calls to perform user file storage operations, import the following packages.

    import com.amazonaws.mobile.config.AWSConfiguration; import com.amazonaws.mobileconnectors.s3.transferutility.*;
  4. Add the following code to the onCreate method of your main or startup activity. This will establish a connection with AWS Mobile. AWSMobileClient is a singleton that will be an interface for your AWS services.

    import com.amazonaws.mobile.client.AWSMobileClient; public class YourMainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AWSMobileClient.getInstance().initialize(this).execute(); } }
Android - Kotlin

Set up AWS Mobile SDK components as follows:

  1. Add the following to app/build.gradle:

    dependencies { implementation ('com.amazonaws:aws-android-sdk-mobile-client:2.6.+@aar') { transitive = true } implementation 'com.amazonaws:aws-android-sdk-s3:2.6.+' implementation 'com.amazonaws:aws-android-sdk-cognito:2.6.+' }

    Perform a Gradle Sync to download the AWS Mobile SDK components into your app

  2. Add the following to AndroidManifest.xml:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application ... > <!- . . . -> <service android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService" android:enabled="true" /> <!- . . . -> </application>
  3. For each Activity where you make calls to perform user file storage operations, import the following packages.

    import com.amazonaws.mobile.config.AWSConfiguration; import com.amazonaws.mobileconnectors.s3.transferutility.*;
  4. Add the following code to the onCreate method of your main or startup activity. This will establish a connection with AWS Mobile. AWSMobileClient is a singleton that will be an interface for your AWS services.

    import com.amazonaws.mobile.client.AWSMobileClient; class MainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AWSMobileClient.getInstance().initialize(this).execute() } }
iOS - Swift

Set up AWS Mobile SDK components as follows:

  1. Add the following to Podfile that you configure to install the AWS Mobile SDK:

    platform :ios, '9.0' target :'YOUR-APP-NAME' do use_frameworks! pod 'AWSMobileClient', '~> 2.6.13' # For AWSMobileClient pod 'AWSS3', '~> 2.6.13' # For file transfers pod 'AWSCognito', '~> 2.6.13' # For data sync # other pods end

    Run pod install --repo-update before you continue.

    If you encounter an error message that begins "[!] Failed to connect to GitHub to update the CocoaPods/Specs . . .", and your internet connectivity is working, you may need to update openssl and Ruby.

  2. Add the following imports to the classes that perform user file storage operations:

    import AWSCore import AWSS3
  3. Add the following code to your AppDelegate to establish a run-time connection with AWS Mobile.

    import UIKit import AWSCore import AWSMobileClient @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { //Instantiate AWSMobileClient to establish AWS user credentials return AWSMobileClient.sharedInstance().interceptApplication(application, didFinishLaunchingWithOptions: launchOptions) } }

Implement Storage Operations

Once your backend is setup and connected to your app, use the following steps to upload and download a file using the SDK's transfer utility.

Upload a File

Android - JavaAndroid - KotliniOS - Swift
Android - Java

To upload a file to an Amazon S3 bucket, use AWSMobileClient to get the AWSConfiguration and AWSCredentialsProvider, then create the TransferUtility object. AWSMobileClient expects an activity context for resuming an authenticated session and creating the credentials provider.

The following example shows using the TransferUtility `in the context of an Activity. If you are creating :code:`TransferUtility from an application context, you can construct the AWSCredentialsProvider and pass it into TransferUtility to use in forming the AWSConfiguration object.. The TransferUtility will check the size of file being uploaded and will automatically switch over to using multi-part uploads if the file size exceeds 5 MB.

import android.app.Activity; import android.util.Log; import com.amazonaws.mobile.client.AWSMobileClient; import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility; import com.amazonaws.mobileconnectors.s3.transferutility.TransferState; import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver; import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener; import com.amazonaws.services.s3.AmazonS3Client; import java.io.File; public class YourActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { AWSMobileClient.getInstance().initialize(this).execute(); uploadWithTransferUtility(); } private void uploadWithTransferUtility() { TransferUtility transferUtility = TransferUtility.builder() .context(getApplicationContext()) .awsConfiguration(AWSMobileClient.getInstance().getConfiguration()) .s3Client(new AmazonS3Client(AWSMobileClient.getInstance().getCredentialsProvider())) .build(); TransferObserver uploadObserver = transferUtility.upload( "s3Folder/s3Key.txt", new File("/path/to/file/localFile.txt")); // Attach a listener to the observer to get state update and progress notifications uploadObserver.setTransferListener(new TransferListener() { @Override public void onStateChanged(int id, TransferState state) { if (TransferState.COMPLETED == state) { // Handle a completed upload. } } @Override public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) { float percentDonef = ((float) bytesCurrent / (float) bytesTotal) * 100; int percentDone = (int)percentDonef; Log.d("YourActivity", "ID:" + id + " bytesCurrent: " + bytesCurrent + " bytesTotal: " + bytesTotal + " " + percentDone + "%"); } @Override public void onError(int id, Exception ex) { // Handle errors } }); // If you prefer to poll for the data, instead of attaching a // listener, check for the state and progress in the observer. if (TransferState.COMPLETED == uploadObserver.getState()) { // Handle a completed upload. } Log.d("YourActivity", "Bytes Transferrred: " + uploadObserver.getBytesTransferred()); Log.d("YourActivity", "Bytes Total: " + uploadObserver.getBytesTotal()); } }
Android - Kotlin

To upload a file to an Amazon S3 bucket, use AWSMobileClient to get the AWSConfiguration and AWSCredentialsProvider, then create the TransferUtility object. AWSMobileClient expects an activity context for resuming an authenticated session and creating the credentials provider.

The following example shows using the TransferUtility `in the context of an Activity. If you are creating :code:`TransferUtility from an application context, you can construct the AWSCredentialsProvider and pass it into TransferUtility to use in forming the AWSConfiguration object.. The TransferUtility will check the size of file being uploaded and will automatically switch over to using multi-part uploads if the file size exceeds 5 MB.

import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log import com.amazonaws.AmazonServiceException import com.amazonaws.mobile.client.AWSMobileClient import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener import com.amazonaws.mobileconnectors.s3.transferutility.TransferState import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility import com.amazonaws.services.s3.AmazonS3Client import kotlinx.android.synthetic.main.activity_main.* import java.io.File; import java.io.File; class MainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate() AWSMobileClient.getInstance().initialize(this).execute() uploadWithTransferUtility( "s3Folder/s3Key.txt" File("/path/to/file/localfile.txt") ) } private fun uploadWithTransferUtility(remote: String, local: File) { val transferUtility = TransferUtility.builder() .context(this.applicationContext) .awsConfiguration(AWSMobileClient.getInstance().configuration) .s3Client(AmazonS3Client(AWSMobileClient.getInstance().credentialsProvider)) .build() val uploadObserver = transferUtility.upload(remote, local) uploadObserver.transferListener = object : TransferListener() { override fun onStateChanged(id: Int, state: TransferState) { if (state == TransferState.COMPLETED) { // Handle a completed upload } } override fun onProgressChanged(id: Int, current: Long, total: Long) { val done = (((current.toDouble() / total) * 100.0).toInt()) Log.d(TAG, "ID: $id, percent done = $done") } override fun onError(id: Int, ex: Exception) { // Handle errors } } // If you prefer to poll for the data, instead of attaching a // listener, check for the state and progress in the observer. if (uploadObserver.state == TransferState.COMPLETED) { // Handle a completed upload. } } }
iOS - Swift

The following example shows how to upload a file to an Amazon S3 bucket.

func uploadData() { let data: Data = Data() // Data to be uploaded let expression = AWSS3TransferUtilityUploadExpression() expression.progressBlock = {(task, progress) in DispatchQueue.main.async(execute: { // Do something e.g. Update a progress bar. }) } var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock? completionHandler = { (task, error) -> Void in DispatchQueue.main.async(execute: { // Do something e.g. Alert a user for transfer completion. // On failed uploads, `error` contains the error object. }) } let transferUtility = AWSS3TransferUtility.default() transferUtility.uploadData(data, bucket: "YourBucket", key: "YourFileName", contentType: "text/plain", expression: expression, completionHandler: completionHandler).continueWith { (task) -> AnyObject! in if let error = task.error { print("Error: \(error.localizedDescription)") } if let _ = task.result { // Do something with uploadTask. } return nil; } }

Download a File

Android - JavaAndroid - KotliniOS - Swift
Android - Java

To download a file from an Amazon S3 bucket, use AWSMobileClient to get the AWSConfiguration and AWSCredentialsProvider to create the TransferUtility object. AWSMobileClient expects an activity context for resuming an authenticated session and creating the .

The following example shows using the TransferUtility in the context of an Activity. If you are creating TransferUtility from an application context, you can construct the AWSCredentialsProvider and pass it into TransferUtility to use in forming the AWSConfiguration object.

import android.app.Activity; import android.util.Log; import com.amazonaws.mobile.client.AWSMobileClient; import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility; import com.amazonaws.mobileconnectors.s3.transferutility.TransferState; import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver; import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener; import com.amazonaws.services.s3.AmazonS3Client; import java.io.File; public class YourActivity extends Activity { public void dowloadData() { AWSMobileClient.getInstance().initialize(this, new AWSStartupHandler() { @Override public void onComplete() { downloadWithTransferUtility(); } }).execute(); } public void downloadWithTransferUtility() { TransferUtility transferUtility = TransferUtility.builder() .context(getApplicationContext()) .awsConfiguration(AWSMobileClient.getInstance().getConfiguration()) .s3Client(new AmazonS3Client(AWSMobileClient.getInstance().getCredentialsProvider())) .build(); TransferObserver downloadObserver = transferUtility.download( "s3Folder/s3Key.txt", new File("/path/to/file/localFile.txt")); // Attach a listener to the observer to get state update and progress notifications downloadObserver.setTransferListener(new TransferListener() { @Override public void onStateChanged(int id, TransferState state) { if (TransferState.COMPLETED == state) { // Handle a completed upload. } } @Override public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) { float percentDonef = ((float)bytesCurrent/(float)bytesTotal) * 100; int percentDone = (int)percentDonef; Log.d("MainActivity", " ID:" + id + " bytesCurrent: " + bytesCurrent + " bytesTotal: " + bytesTotal + " " + percentDone + "%"); } @Override public void onError(int id, Exception ex) { // Handle errors } }); // If you prefer to poll for the data, instead of attaching a // listener, check for the state and progress in the observer. if (TransferState.COMPLETED == downloadObserver.getState()) { // Handle a completed upload. } Log.d("YourActivity", "Bytes Transferrred: " + downloadObserver.getBytesTransferred()); Log.d("YourActivity", "Bytes Total: " + downloadObserver.getBytesTotal()); } }
Android - Kotlin

To download a file from an Amazon S3 bucket, use AWSMobileClient to get the AWSConfiguration and AWSCredentialsProvider to create the TransferUtility object. AWSMobileClient expects an activity context for resuming an authenticated session and creating the .

The following example shows using the TransferUtility in the context of an Activity. If you are creating TransferUtility from an application context, you can construct the AWSCredentialsProvider and pass it into TransferUtility to use in forming the AWSConfiguration object.

import android.app.Activity; import android.util.Log; import com.amazonaws.mobile.client.AWSMobileClient; import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility; import com.amazonaws.mobileconnectors.s3.transferutility.TransferState; import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver; import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener; import com.amazonaws.services.s3.AmazonS3Client; import java.io.File; class MainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate() AWSMobileClient.getInstance().initialize(this).execute() downloadWithTransferUtility( "s3Folder/s3Key.txt" File("/path/to/file/localfile.txt") ) } private fun downloadWithTransferUtility(remote: String, local: File) { val transferUtility = TransferUtility.builder() .context(getApplicationContext) .awsConfiguration(AWSMobileClient.getInstance().configuration) .s3Client(AmazonS3Client(AWSMobileClient.getInstance().credentialsProvider)) .build() val downloadObserver = transferUtility.download(remote, local) downloadObserver.transferListener = object : TransferListener() { override fun onStateChanged(id: Int, state: TransferState) { if (state == TransferState.COMPLETED) { // Handle a completed upload } } override fun onProgressChanged(id: Int, current: Long, total: Long) { try { val done = (((current.toDouble() / total) * 100.0).toInt()) //as Int Log.d("downloadObserver", "DOWNLOAD - - ID: $id, percent done = $done") } catch (e: Exception) { // Handle errors } } override fun onError(id: Int, ex: Exception) { // Handle errors } } // If you prefer to poll for the data, instead of attaching a // listener, check for the state and progress in the observer. if (downloadObserver.state == TransferState.COMPLETED) { // Handle a completed upload. } } }
iOS - Swift

The following example shows how to download a file from an Amazon S3 bucket.

func downloadData() { let expression = AWSS3TransferUtilityDownloadExpression() expression.progressBlock = {(task, progress) in DispatchQueue.main.async(execute: { // Do something e.g. Update a progress bar. }) } var completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock? completionHandler = { (task, URL, data, error) -> Void in DispatchQueue.main.async(execute: { // Do something e.g. Alert a user for transfer completion. // On failed downloads, `error` contains the error object. }) } let transferUtility = AWSS3TransferUtility.default() transferUtility.downloadData( fromBucket: "YourBucket", key: "YourFileName", expression: expression, completionHandler: completionHandler ).continueWith { (task) -> AnyObject! in if let error = task.error { print("Error: \(error.localizedDescription)") } if let _ = task.result { // Do something with downloadTask. } return nil; } }

Next Steps