× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How to upload images to AWS S3 in swift

Julián Romero
Jan 16, 2016
<p>Uploading an image to <a href="https://aws.amazon.com/s3">Amazon S3</a> is quite straightforward once you extract the relevant code from the <a href="https://github.com/awslabs/aws-sdk-ios-samples/tree/master/S3TransferManager-Sample/Swift">official sample project</a>.</p> <p>We need to setup your Xcode project to build the <a href="https://github.com/aws/aws-sdk-ios">AWS SDK</a>. We only need the <a href="https://github.com/aws/aws-sdk-ios/tree/master/AWSS3">AWSS3</a> component. Let's use <a href="http://cocoapods.org/">cocoapods</a> for simplicity. </p> <pre># Podfile source 'https://github.com/CocoaPods/Specs.git' platform :ios, '9.0' pod 'AWSS3', '~&gt; 2.3.3' use_frameworks! </pre> <p>Setup a new swift project in Xcode and run <code>pod install</code>. Then open the created Xcode workspace.</p> <p>Once AWSS3 framework is ready, we need to configure the authentication:</p> <pre>import AWSS3 // configure S3 let S3BucketName = "&lt;#bucket#&gt;" // configure authentication with Cognito let CognitoPoolID = "&lt;#cognito-pool-id#&gt;" let Region = AWSRegionType.&lt;#region#&gt; let credentialsProvider = AWSCognitoCredentialsProvider(regionType:Region, identityPoolId:CognitoPoolID) let configuration = AWSServiceConfiguration(region:Region, credentialsProvider:credentialsProvider) AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration </pre> <p>Replace the placeholders with your actual S3 bucket name, your <a href="https://console.aws.amazon.com/cognito/">Cognito</a> pool ID and region. See <a href="http://docs.aws.amazon.com/mobile/sdkforios/developerguide/s3transfermanager.html">how to configure policies</a> to allow a cognito pool to access S3.</p> <p>Add any image to your project and get its URL like this:</p> <pre>let ext = "png" let imageURL = NSBundle.mainBundle().URLForResource("&lt;#image-name#&gt;", withExtension: ext)!</pre> <p>Prepare the actual uploader:</p> <pre>let uploadRequest = AWSS3TransferManagerUploadRequest() uploadRequest.body = imageURL uploadRequest.key = NSProcessInfo.processInfo().globallyUniqueString + "." + ext uploadRequest.bucket = S3BucketName uploadRequest.contentType = "image/" + ext</pre> <p>You can use the image file name as S3 key if you prefer it with <code>imageURL.lastPathComponent</code>.</p> <p>And finally push the image to server:</p> <pre>let transferManager = AWSS3TransferManager.defaultS3TransferManager() transferManager.upload(uploadRequest).continueWithBlock { (task) -&gt; AnyObject! in if let error = task.error { print("Upload failed ❌ (\(error))") } if let exception = task.exception { print("Upload failed ❌ (\(exception))") } if task.result != nil { let s3URL = NSURL(string: "http://s3.amazonaws.com/\(S3BucketName)/\(uploadRequest.key!)")! print("Uploaded to:\n\(s3URL)") } else { print("Unexpected empty result.") } return nil }</pre> <p>That's it. You can save the uploaded image URL in your database, use it to show it in an image view, etc. For instance, you can easily create an <code>UIImage</code> instance:</p> <pre> let image = UIImage(data: NSData(contentsOfURL: s3URL)!)</pre> <p>If you want the image to be public configure the S3 bucket with this policy:</p> <pre>{ "Statement": [ { "Action": "s3:GetObject", "Effect": "Allow", "Principal": "*", "Resource": "arn:aws:s3:::your-bucket-name/*", "Sid": "AddPerm" } ] }</pre> <p>Don't forget to use your actual S3 bucket name.</p> <p>Xcode <a href="https://github.com/djromero/S3UploaderPlayground">playground available in GitHub</a>.</p> <p> </p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus