Upload Image to AWS S3 Bucket. In Swift.

In this blog post I am going to share with you how to upload an image to Amazon AWS S3 Bucket. I have split information into smaller videos and it will cover:
http://swiftdeveloperblog.com/image-upload-example/
http://swiftdeveloperblog.com/upload-image-to-aws-s3-bucket-in-swift/
  • Create AWS S3 Bucket
  • Edit S3 Bucket policy to allow users read files from it
  • Use AWS Cognito to create a Federated Identity Pool
  • Install CocoaPods and use it to download AWS SDK for iOS
  • Write Swift code to upload image to AWS S3 Bucket

Introduction


Create AWS S3 Bucket


AWS Bucket Policy 
  1. {
  2. "Version": "2008-10-17",
  3. "Statement": [
  4. {
  5. "Sid": "AddPerm",
  6. "Effect": "Allow",
  7. "Principal": "*",
  8. "Action": "s3:GetObject",
  9. "Resource": "arn:aws:s3:::learn-swift/*"
  10. }
  11. ]
  12. }

Create Federated Identity Pool with AWS Cognito


Download and Setup AWS SDK for iOS Platform


Write Code to Upload Image to AWS S3 Bucket


Select image with UIImagePickerController and upload it to AWS S3 bucket


Upload Image to AWS S3 Bucket. Source code in Swift

  1. import UIKit
  2. import AWSCore
  3. import AWSS3
  4. import Photos
  5. class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
  6. var showImagePickerButton: UIButton!
  7. var myImageView: UIImageView!
  8. var selectedImageUrl: NSURL!
  9. var myActivityIndicator: UIActivityIndicatorView!
  10. override func viewDidLoad() {
  11. super.viewDidLoad()
  12. // Do any additional setup after loading the view, typically from a nib.
  13. setupImagePickerButton()
  14. setupImageView()
  15. setupUploadButton()
  16. setUpActivityIndicator()
  17. }
  18. override func didReceiveMemoryWarning() {
  19. super.didReceiveMemoryWarning()
  20. // Dispose of any resources that can be recreated.
  21. }
  22. override func viewWillAppear(animated: Bool) {
  23. super.viewWillAppear(animated)
  24. }
  25. func startUploadingImage()
  26. {
  27. var localFileName:String?
  28. if let imageToUploadUrl = selectedImageUrl
  29. {
  30. let phResult = PHAsset.fetchAssetsWithALAssetURLs([imageToUploadUrl], options: nil)
  31. localFileName = phResult.firstObject?.filename
  32. }
  33. if localFileName == nil
  34. {
  35. return
  36. }
  37. myActivityIndicator.startAnimating()
  38. // Configure AWS Cognito Credentials
  39. let myIdentityPoolId = ""
  40. let credentialsProvider:AWSCognitoCredentialsProvider = AWSCognitoCredentialsProvider(regionType:AWSRegionType.-- USEast1, identityPoolId: myIdentityPoolId)
  41. let configuration = AWSServiceConfiguration(region:AWSRegionType.-- USEast1, credentialsProvider:credentialsProvider)
  42. AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration
  43. // Set up AWS Transfer Manager Request
  44. let S3BucketName = "learn-swift"
  45. let remoteName = localFileName!
  46. let uploadRequest = AWSS3TransferManagerUploadRequest()
  47. uploadRequest.body = generateImageUrl(remoteName)
  48. uploadRequest.key = remoteName
  49. uploadRequest.bucket = S3BucketName
  50. uploadRequest.contentType = "image/jpeg"
  51. let transferManager = AWSS3TransferManager.defaultS3TransferManager()
  52. // Perform file upload
  53. transferManager.upload(uploadRequest).continueWithBlock { (task) -> AnyObject! in
  54. dispatch_async(dispatch_get_main_queue()) {
  55. self.myActivityIndicator.stopAnimating()
  56. }
  57. if let error = task.error {
  58. print("Upload failed with error: (\(error.localizedDescription))")
  59. }
  60. if let exception = task.exception {
  61. print("Upload failed with exception (\(exception))")
  62. }
  63. if task.result != nil {
  64. let s3URL = NSURL(string: "https://s3.amazonaws.com/\(S3BucketName)/\(uploadRequest.key!)")!
  65. print("Uploaded to:\n\(s3URL)")
  66. // Remove locally stored file
  67. self.remoteImageWithUrl(uploadRequest.key!)
  68. dispatch_async(dispatch_get_main_queue()) {
  69. self.displayAlertMessage()
  70. }
  71. }
  72. else {
  73. print("Unexpected empty result.")
  74. }
  75. return nil
  76. }
  77. }
  78. func displayAlertMessage()
  79. {
  80. let alertController = UIAlertController(title: "Alert title", message: "Image has been uploaded", preferredStyle: .Alert)
  81. let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
  82. // Code in this block will trigger when OK button tapped.
  83. print("Ok button tapped");
  84. }
  85. alertController.addAction(OKAction)
  86. self.presentViewController(alertController, animated: true, completion:nil)
  87. }
  88. func generateImageUrl(fileName: String) -> NSURL
  89. {
  90. let fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory().stringByAppendingString(fileName))
  91. let data = UIImageJPEGRepresentation(myImageView.image!, 0.6)
  92. data!.writeToURL(fileURL, atomically: true)
  93. return fileURL
  94. }
  95. func remoteImageWithUrl(fileName: String)
  96. {
  97. let fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory().stringByAppendingString(fileName))
  98. do {
  99. try NSFileManager.defaultManager().removeItemAtURL(fileURL)
  100. } catch
  101. {
  102. print(error)
  103. }
  104. }
  105. func setupImagePickerButton()
  106. {
  107. let button = UIButton(type: UIButtonType.System) as UIButton
  108. let xPostion:CGFloat = 50
  109. let yPostion:CGFloat = 100
  110. let buttonWidth:CGFloat = 150
  111. let buttonHeight:CGFloat = 45
  112. button.frame = CGRectMake(xPostion, yPostion, buttonWidth, buttonHeight)
  113. button.backgroundColor = UIColor.lightGrayColor()
  114. button.setTitle("Select image", forState: UIControlState.Normal)
  115. button.tintColor = UIColor.blackColor()
  116. button.addTarget(self, action: #selector(ViewController.displayImagePickerButtonTapped) , forControlEvents: .TouchUpInside)
  117. self.view.addSubview(button)
  118. }
  119. func setupImageView()
  120. {
  121. myImageView = UIImageView()
  122. let xPostion:CGFloat = 50
  123. let yPostion:CGFloat = 200
  124. let buttonWidth:CGFloat = 200
  125. let buttonHeight:CGFloat = 200
  126. myImageView.frame = CGRectMake(xPostion, yPostion, buttonWidth, buttonHeight)
  127. self.view.addSubview(myImageView)
  128. }
  129. func setupUploadButton()
  130. {
  131. let rightBarButton = UIBarButtonItem(title: "Upload", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ViewController.startUploadingImage))
  132. self.navigationItem.rightBarButtonItem = rightBarButton
  133. }
  134. func setUpActivityIndicator()
  135. {
  136. //Create Activity Indicator
  137. myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
  138. // Position Activity Indicator in the center of the main view
  139. myActivityIndicator.center = view.center
  140. // If needed, you can prevent Acivity Indicator from hiding when stopAnimating() is called
  141. myActivityIndicator.hidesWhenStopped = true
  142. myActivityIndicator.backgroundColor = UIColor.whiteColor()
  143. view.addSubview(myActivityIndicator)
  144. }
  145. func displayImagePickerButtonTapped() {
  146. let myPickerController = UIImagePickerController()
  147. myPickerController.delegate = self;
  148. myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
  149. self.presentViewController(myPickerController, animated: true, completion: nil)
  150. }
  151. func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
  152. {
  153. selectedImageUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
  154. myImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
  155. myImageView.backgroundColor = UIColor.clearColor()
  156. myImageView.contentMode = UIViewContentMode.ScaleAspectFit
  157. self.dismissViewControllerAnimated(true, completion: nil)
  158. }
  159. }
I hope this blog post was valuable to you and if it was, please click on the Like button of that youtube video or subscribe(on the right side panel) to my blog, so that you can receive notification when a new free video tutorial becomes available.
Happy coding! 🙂

Comments

Popular posts from this blog

Retrofit Android Example Tutorial

UISearchController Tutorial: Getting Started

Create a gradient color view in iOS using Swift 3 and XCode 8