Getting started with AWS S3 — To upload image via API gateway — sample iOS app

AWS + Lambda + iOS

Sign Up

AWS S3 Console
Confirm your identity
Complete signup

Create bucket

Create bucket
Disable block all public access

Bucket Permission

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::bucketsampleios/*"
}
]
}

Setup Lambda Funtion

Lambda
Create function
Setup basic information
import json
import base64
import boto3
import uuid
file_name = "content.png"
s3_path = str(uuid.uuid4()) + file_name
bucket_name = "BUCKET_NAME"
def lambda_handler(event, context):
s3 = boto3.client("s3")
get_file_content = event["content"]
decode_content = base64.b64decode(get_file_content)
s3_upload = s3.put_object(Bucket=bucket_name, Key=s3_path, Body=decode_content)
return {
"statusCode": 200,
"body": json.dumps(s3_path)
}

Setup API Gateway

Create new API
Actions
Create Resource
Add PUT method
Add lambda function
{
"content" : "$input.body"
}
Mapping Templates
Deploy API
Invoke URL

Sample iOS app

let image = UIImage(named: "apple")!
if let imageData = image.pngData(){
let header : HTTPHeaders = ["Content-Type": "image/png"]
let url = "INVOKE_URL"
AF.upload(imageData, to: url, method: .put, headers: header)
.responseObject { (response:AFDataResponse<T>) in
switch response.result{
case .success(let value):
onSuccess(value)
case .failure(let error):
onError(error)
return
}}}

 iOS Developer @nfnlabs, Chennai. Here to share best practices learned through my experience. Reach me on https://www.linkedin.com/in/ashokkumar-b-26026913a/