Last active
December 20, 2024 11:30
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
Author
Catherine-K-George
commented
Jun 6, 2021
•
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)
How are you generating the presigned url in swift?
Thanks for this, I was tryin got get background iOS uploads to work with Supabase's signed urls, couldn't figure out what was wrong - I think specifying "PUT" did the trick
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment