Skip to content

Instantly share code, notes, and snippets.

@Catherine-K-George
Last active August 6, 2023 08:47
Show Gist options
  • Save Catherine-K-George/70fbffd979f8c8421d0ea04fee52e90e to your computer and use it in GitHub Desktop.
Save Catherine-K-George/70fbffd979f8c8421d0ea04fee52e90e to your computer and use it in GitHub Desktop.
File upload to AWS S3 with pre-signed URL iOS/Swift 5
import AWSS3
class AWSS3Uploader {
/// Creates a upload request for uploading the specified file to a presigned remote URL
///
/// - Parameters:
/// - fileURL: The URL of the file to upload.
/// - remoteURL: The presigned URL
/// - completion: The completion handler to call when the upload request is complete.
class func upload(_ fileURL: URL, toPresignedURL remoteURL: URL, completion: @escaping (Result<URL?, Error>) -> Void) {
var request = URLRequest(url: remoteURL )
request.cachePolicy = .reloadIgnoringLocalCacheData
request.httpMethod = "PUT"
let uploadTask = URLSession.shared.uploadTask(with: request, fromFile: fileURL, completionHandler: { (data, response, error) in
if let error = error {
completion(.failure(error))
return
}
guard response != nil, data != nil else {
completion(.success(nil))
return
}
completion(.success(fileURL))
})
uploadTask.resume()
}
}
@Catherine-K-George
Copy link
Author

Catherine-K-George commented Jun 6, 2021

// Usage
AWSS3Uploader().upload(fileURL, toPresignedURL: remoteURL) { (result) in
    switch result {
    case .success(let url):
        print("File uploaded: ", url)
    case .failure(let error):
        print("Upload failed: ", error.localizedDescription)
    }
} 

@jdowd7
Copy link

jdowd7 commented Aug 25, 2022

Thanks for the snip!

Created an async wrapper for it:

private func upload(_ fileURL: URL, toPresignedURL remoteURL: URL) async -> Result<URL?, Error> {
  return await withCheckedContinuation { continuation in
    upload(fileURL, toPresignedURL: remoteURL) { (result) in
      switch result {
      case .success(let url):
          print("File uploaded: ", url)
      case .failure(let error):
          print("Upload failed: ", error.localizedDescription)
      }
      continuation.resume(returning: result)
    }
  }
}

Call it:

let result = await upload(localURL, toPresignedURL: signedURL)

@trevordevs
Copy link

How are you generating the presigned url in swift?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment