How to Use Amazon s3 as Image Hosting Server to Reduce Website’s Bandwidth Usage

Nowadays, most developers are opting to use Amazon S3 image hosting service to increase a page speed.  to make it available on the web. And for those who don’t know what Amazon s3 is, It is a simple storage service(s3) that allows developers a secure, scalable, and inexpensive data storage.

So in this tutorial, we’re going demonstrate how to use Amazon s3 as an Image hosting server to minimize the bandwidth usage.

Getting Started

To Upload image/video/file on Amazon S3 upload we need following settings in AWS.

Create Bucket where your data will be saved and for that follow instruction in given below link:
http://docs.aws.amazon.com/AmazonS3/latest/gsg/CreatingABucket.html

Get Access Key ID and Secret key of AWS from
http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSGettingStartedGuide/AWSCredentials.html

Now, we start code in XCODE for upload files from iPhone.

Create a new project under the file menu and select Single View Application.

How to Use Amazon s3 as Image Hosting Server to Reduce Website’s Bandwidth Usage

In the next tab, give a name to your project. Here, we’re naming it as SOAWSUpload.

s3upload2

Add pod ‘AWSS3’, ‘~> 2.4’ file in your Podfile and install pod.

NOTE:- Please find complete guideline how to install pod file in your Xcode project.

Once when you installed pod then create a bridging file by following steps.

  • Add a new file to Xcode (File > New > File), then select “Source” and click “Header File“.

s3upload3

s3upload4

  • Name your file “YourProjectName-Bridging-Header.h”
  • Then click “Next” and then “Create”

s3upload5

  • Once header file generated then go to Project -> Target -> Swift Compiler – Code Generation -> Objective-C Bridging Header and set a path of Header file.

s3upload6

 

s3upload7
Then import AWSS3 in bridging file.

#import <AWSCore.h>
#import <AWSS3.h>

Now declare constant of BUCKET NAME, AWS APP KEY and AWS SECRET KEY in “ViewController.swift”

let bucketName = "<bucket name>"
let accessKey = "AKIAIOSFODNN7EXAMPLE"
let SecretKey = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"

Add following code snippet in viewDidLoad() for configure AWS access

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

let credentialsProvider: AWSStaticCredentialsProvider = AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: SecretKey)
let configuration: AWSServiceConfiguration = AWSServiceConfiguration(region: .USWest2, credentialsProvider: credentialsProvider)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration

}

Now fetch image from your device gallery and save that image to Document Directory and get path of document directory in global String variable “strURL” on “getImageFromGallary()” action

//MARK: Fetch image from Gallery
@IBAction func getImageFromGallary(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true;
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion: nil)
}

// MARK: - UIImagePickerControllerDelegate Methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
strURL = self.saveImageInDocumentDirectory(image)
dismissViewControllerAnimated(true, completion: nil)
}

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}


//MARK: Save image to document directory
func saveImageInDocumentDirectory(img : UIImage) -> String {
let fileManager = NSFileManager.defaultManager()
let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("demo.jpg") as String
let imageData = UIImageJPEGRepresentation(img, 0.5)
fileManager.createFileAtPath(path, contents: imageData, attributes: nil)
return path
}

Now start uploading file on AWS S3 by following code snippet

@IBAction func uploadOnAWSS3(sender: AnyObject) {
// Set up the S3 upload request manager
let uploadRequest = AWSS3TransferManagerUploadRequest()
// set the bucket
uploadRequest.bucket = bucketName
// Make Image public to view so set it as Public Read
uploadRequest.ACL = .PublicRead
// Set the image's name
uploadRequest.key = "demoimage.jpg"
// Set the content type
uploadRequest.contentType = "image/jpeg"
// Set local file path
uploadRequest.body = NSURL(fileURLWithPath: strURL)

//Get Progress of uploading date by Block
uploadRequest?.uploadProgress = {(bytesSent:Int64, totalBytesSent:Int64, totalBytesExpectedToSend:Int64) in

dispatch_sync(dispatch_get_main_queue(), { () -> Void in
print(totalBytesSent)
print(totalBytesExpectedToSend)
})
}

// Setup request for Upload
let transferManager:AWSS3TransferManager = AWSS3TransferManager.defaultS3TransferManager()

transferManager.upload(uploadRequest).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock:{
task -> AnyObject in
// Will get response status here.
if(task.error != nil){
// If got error then the get description from here.
print("%@", task.error!.localizedDescription);
}else{
// Else we successfully uploaded image.
// Url of S3 uploaded image should be like below
print("https://s3.amazonaws.com/s3-demo-swift/\(bucketName)/demoimage.jpg");
}
return ""
})
}

Done! This is how you can use Amazon hosting services as image hosting server for your iOS app. However, if you face any problem implementing it, you can either write a comment below or contact our developers directly for help.

The main benefit of using Amazon s3 hosting is that you can upload your users’ images/video on a separate amazon server to reduce the bandwidth usage.

However, if you’re not a technical person, then using Amazon hosting services might seem like a daunting task. But, if you do want to use it for your iOS app, then you can always contact us for the same. We’re an iPhone app development company and we’ve been this industry for more than 5 years. Additionally, we’ve already developed 2000+ iPhone apps meaning not only we know every aspect of developing iPhone app from scratch, but we know how to develop an iPhone app that runs efficiently on all devices.

You can also download the source code of Amazon S3 demo from Github.

This page was last edited on October 3rd, 2016, at 18:40.
 
 

Wanna Boost Your Page Speed? Contact us to Integrate Amazon S3 Image Hosting Service.

Get your free consultation now