Skip to content

maximbilan/Swift-Amazon-S3-Uploading-Tutorial

Repository files navigation

How to upload a file to Amazon S3 using Swift

I would like to share a simple tutorial how to upload a to Amazon S3 in iOS using Swift. Let’s go.

alt tag

We need to add Amazon S3 framework to your project.
In this example I will do this with helping Cocoapods.

Create a Podfile:

platform :ios, '8.0'
inhibit_all_warnings!
use_frameworks!
target 'AmazonS3Upload' do
pod 'AWSS3'
end

Run the next command from Terminal:

pod install

Open the generated workspace. And after that we can implement uploading of files using frameworks from Pods.

We need to import 2 modules:

import AWSS3
import AWSCore

Set up a AWS configuration using your credentials. For example:

let accessKey = "..."
let secretKey = "..."
let credentialsProvider = AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: secretKey)
let configuration = AWSServiceConfiguration(region: AWSRegionType.usEast1, credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration

Create an upload request:

let url = ...URL to your file...
let remoteName = "Name of uploaded file"
let S3BucketName = "Name of your bucket on Amazon S3"
let uploadRequest = AWSS3TransferManagerUploadRequest()!
uploadRequest.body = url
uploadRequest.key = remoteName
uploadRequest.bucket = S3BucketName
uploadRequest.contentType = "image/jpeg"
uploadRequest.acl = .publicRead

And upload using AWSS3TransferManager.

let transferManager = AWSS3TransferManager.default()
transferManager?.upload(uploadRequest).continue({ (task: AWSTask) -> Any? in
  if let error = task.error {
    print("Upload failed with error: (\(error.localizedDescription))")
  }
  if let exception = task.exception {
    print("Upload failed with exception (\(exception))")
  }
  if task.result != nil {
    let url = AWSS3.default().configuration.endpoint.url
    let publicURL = url?.appendingPathComponent(uploadRequest.bucket!).appendingPathComponent(uploadRequest.key!)
    print("Uploaded to:\(publicURL)")
  }
  return nil
})