· 9 years ago · Jan 13, 2017, 11:44 AM
1@IBOutlet weak var uploadButton: UIButton!
2@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
3
4override func viewDidLoad() {
5 super.viewDidLoad()
6}
7
8@IBAction func uploadButtonAction(_ sender: UIButton) {
9 uploadWIthAWS()
10}
11
12
13func uploadWIthAWS(){
14
15 uploadButton.isHidden = true
16 activityIndicator.startAnimating()
17
18 let accessKey = "AKIAI6KI5S3YNT"
19 let secretKey = "yXED2s4kJch862"
20
21 let credentialsProvider = AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: secretKey)
22 let configuration = AWSServiceConfiguration(region:AWSRegionType.usEast1, credentialsProvider:credentialsProvider)
23 AWSServiceManager.default().defaultServiceConfiguration = configuration
24
25 let S3BucketName = "iostestpnkbksh"
26 let remoteName = "abc.png"
27 let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(remoteName)
28 let image = UIImage(named: "abc")
29 let data = UIImageJPEGRepresentation(image!, 0.9)
30 do {
31 try data?.write(to: fileURL)
32 }
33 catch {}
34
35
36 //========================Create upload request===========================//
37
38 let uploadRequest : AWSS3TransferManagerUploadRequest = AWSS3TransferManagerUploadRequest()!
39 uploadRequest.body = fileURL
40 uploadRequest.key = remoteName
41 uploadRequest.bucket = S3BucketName
42 uploadRequest.contentType = "image/jpeg"
43 uploadRequest.acl = .publicRead
44
45 //=======================Upload to Amazon S3=============================//
46
47 let transferManager = AWSS3TransferManager.default()
48
49transferManager?.upload(uploadRequest).continue(with: AWSExecutor.mainThread(), with: { (task: AWSTask) -> AnyObject? in
50
51
52 DispatchQueue.main.async {
53 self.uploadButton.isHidden = false
54 self.activityIndicator.stopAnimating()
55 }
56
57 if task.isCompleted {
58
59 print(task.isCompleted)
60 print(task.result ?? "nil")
61
62 }
63 if let error = task.error {
64 print("Upload failed with error: ((error.localizedDescription))")
65 }
66 if let exception = task.exception {
67 print("Upload failed with exception ((exception))")
68 }
69
70 if task.result != nil {
71
72 let url = AWSS3.default().configuration.endpoint.url
73 let publicURL = url?.appendingPathComponent(uploadRequest.bucket!).appendingPathComponent(uploadRequest.key!)
74 print("Uploaded to:(publicURL!)")
75
76 // let s3URL = NSURL(string: "http://s3.amazonaws.com/(S3BucketName)/(uploadRequest.key!)")!
77 // print("Uploaded to:n(s3URL)")
78
79
80 }
81 else{
82
83 }
84 return nil
85 })
86
87
88}