Getting Started – Amazon S3 (Amazon Simple Storage Service)

Getting Started – Amazon S3 (Amazon Simple Storage Service)

How to upload images and videos to AWS S3 in swift with quick steps

Nowadays AWS S3 Bucket is a very popular library to upload files like image, video, audio, etc. We are going to use AWS iOS SDK and we will create an AWSS3Manager class, using this manager class, we will upload any files by writing just one line code. AWSS3Manager class will make it super easy to upload any type of files. Let’s not wait anymore and start coding.

Setup Project

We suppose you already have AWS S3 Bucket setup, bucket name, we will need these information.
– Create a new project or you can use your existing project as well.
– Open a terminal and navigate to your project.
– Run a command: pod init
–Open the Podfile and write: pod ‘AWSS3’
–Now open the terminal again and run the command: pod install

Now your project file will look like below.

Now open AWS_S3App.xcworkspace file from onward.

Setup AWS Credentials

Open AppDelegate.swift file and make below changes

1 import AWSS3 framework
2 Call this function to set AWS up credential
3 Change your region based on your AWS account region.

Creating AWSS3Manager Class

Create a new swift file and name it AWSS3Manager
Add below code in this file

import Foundation import UIKit import AWSS3 //1 typealias completionBlock = (_ response: Any?, _ error: Error?) -> Void //2 class AWSS3Manager { static let shared = AWSS3Manager() //3 private init () { }
// Upload image using UIImage object func uploadImage(image: UIImage, completion: completionBlock?) { guard let imageData = image.jpegData(compressionQuality: 1.0) else { let error = NSError(domain:"", code:402, userInfo:[NSLocalizedDescriptionKey: "invalid image"]) completion?(nil, error) return } let tmpPath = NSTemporaryDirectory() as String let fileName: String = ProcessInfo.processInfo.globallyUniqueString + (".jpeg") let filePath = tmpPath + "/" + fileName let fileUrl = URL(fileURLWithPath: filePath) do { try imageData.write(to: fileUrl) self.uploadfile(fileUrl: fileUrl, fileName: fileName, contenType: "image", completion: completion) } catch { let error = NSError(domain:"", code:402, userInfo:[NSLocalizedDescriptionKey: "invalid image"]) completion?(nil, error) } } // Upload video from local path url func uploadVideo(videoUrl: URL,completion: completionBlock?) { let fileName = self.getUniqueFileName(fileUrl: videoUrl) self.uploadfile(fileUrl: videoUrl, fileName: fileName, contenType: "video", completion: completion) } // Get unique file name func getUniqueFileName(fileUrl: URL) -> String { let strExt: String = "." + (URL(fileURLWithPath: fileUrl.absoluteString).pathExtension) return (ProcessInfo.processInfo.globallyUniqueString + (strExt)) } //MARK:- AWS file upload // fileUrl : file local path url // fileName : name of file, like "myimage.jpeg" "" // contenType: file MIME type // completion: completion block when uplaoding is finish, you will get S3 url of upload file here private func uploadfile(fileUrl: URL, fileName: String, contenType: String, completion: completionBlock?) { let uploadRequest = AWSS3TransferManagerUploadRequest()! uploadRequest.body = fileUrl uploadRequest.key = fileName if contenType == "image" { uploadRequest.bucket = NYK_MEDIA_DEV //4 } else { uploadRequest.bucket = NYK_VIDEO_DEV } uploadRequest.contentType = contenType// "image/jpeg" uploadRequest.acl = .publicRead let transferManager = AWSS3TransferManager.default() transferManager.upload(uploadRequest).continueWith { [weak self] (task) -> Any? in if let error = task.error { print("Upload failed with error: (\(error.localizedDescription))") } if task.result != nil { let url = AWSS3.default().configuration.endpoint.url let publicURL = url?.appendingPathComponent(uploadRequest.bucket!).appendingPathComponent(uploadRequest.key!) if let absoluteString = publicURL?.absoluteString { print("Uploaded to:\(absoluteString)") completion?(absoluteString, task.error) } } return nil } } }

1 import AWSS3 framework
2 This is the completion block which executes when uploading finish
3 Create a shared instance of this class
4 Enter your bucket name here

Move to UploadViewController class

Open the nib file and add controls as shown in the below image

– Create an IBOutlet of  activityIndicator: UIActivityIndicatorView!
– Create an IBOutlet of  uploadButton: UIButton!
– Create an IBOutlet of  uploadVideoButton: UIButton!
– Create an IBOutlet of  s3UrlLabel: UILabel!

The code will look like below

Upload Image

Add below code in your tapUploadImage function which is inside your UIViewController class

1 Get your image
2 In the completion block, you will get the uploaded image URL string

Upload Video

Below function is defined under AWSS3Manager class to upload video, we are going to use this

Add below code in your tapUploadVideo function

  Thanks Happy coding

Leave A Comment

Your email address will not be published. Required fields are marked *