Created
May 1, 2020 05:41
-
-
Save kongzii/ad821265ba2a6d8de73c1bcbc68b4694 to your computer and use it in GitHub Desktop.
Download from S3 to local file in Swift
This file contains 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 Foundation | |
import Logging | |
import S3 | |
let LOGGER = Logger(label: "S3") | |
enum S3Error: Error { | |
case runtimeError(String) | |
} | |
public func download( | |
directory: String, | |
from address: String, | |
accessKeyId: String, | |
secretAccessKey: String, | |
endpoint: String | |
) throws -> String { | |
precondition(address.hasPrefix("s3://"), "Invalid S3 address \(address).") | |
precondition(endpoint.hasPrefix("https://"), "Invalid endpoint address \(endpoint).") | |
LOGGER.debug("S3 address \(address).") | |
LOGGER.debug("S3 endpoint \(endpoint).") | |
let s3 = S3( | |
accessKeyId: accessKeyId, | |
secretAccessKey: secretAccessKey, | |
endpoint: endpoint | |
) | |
let splitted = address.components(separatedBy: "/") | |
let bucket = splitted[2] | |
let key = splitted[3...].joined(separator: "/") | |
let name = splitted.last! | |
LOGGER.debug("S3 bucket \(bucket), key \(key), name \(name).") | |
let object = try s3.getObject(S3.GetObjectRequest( | |
bucket: bucket, | |
key: key | |
)).wait() | |
guard let body = object.body else { | |
throw S3Error.runtimeError("Something went wrong with S3 getObject.") | |
} | |
let path = "\(directory)/\(name)" | |
LOGGER.debug("S3 output path \(path).") | |
let url = URL(string: "file://\(path)")! | |
LOGGER.debug("S3 output url \(url).") | |
try body.write(to: url) | |
return path | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment