Skip to content

Instantly share code, notes, and snippets.

@maximbilan
Created February 10, 2017 20:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maximbilan/403ccf3e25885c6a3a4fe19536bac8a6 to your computer and use it in GitHub Desktop.
Save maximbilan/403ccf3e25885c6a3a4fe19536bac8a6 to your computer and use it in GitHub Desktop.
Swift 3 Upload file to Amazon S3 with pre-signed link
func upload(data: Data, urlString: String, mimeType: String, completion: @escaping (Bool, Error?) -> Void) {
let requestURL = URL(string: urlString)!
let client = AFHTTPSessionManager(baseURL: requestURL)
var request = URLRequest(url: requestURL)
request.httpMethod = "PUT"
request.httpBody = data
request.setValue(mimeType, forHTTPHeaderField: "Content-Type")
request.setValue("\(data.count)", forHTTPHeaderField: "Content-Length")
request.setValue("public-read", forHTTPHeaderField: "x-amz-acl")
let task = client?.dataTask(with: request, completionHandler: { (response, responseObject, error) in
print(response ?? "response nil")
print(error ?? "response nil")
completion(error == nil, error)
})
task?.resume()
}
func upload(image: UIImage, urlString: String, mimeType: String, completion: @escaping (Bool, Error?) -> Void) {
let data = UIImageJPEGRepresentation(image, 0.9)!
upload(data: data, urlString: urlString, mimeType: mimeType, completion: completion)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment