Isuru Isuru - 6 months ago 21
Swift Question

Get a reference to the AWSS3 object

I'm uploading a photo from my iOS app to Amazon S3 successfully. I need to get the publicly accessible URL for that photo. Instead of building the URL manually, I use the following way to do that.

let transferManager = AWSS3TransferManager.defaultS3TransferManager()
transferManager.upload(uploadRequest).continueWithBlock { task in
if let error = task.error {
print("Upload failed: \(error.code) - \(error.localizedDescription)")
}
if let exception = task.exception {
print("Upload failed: \(exception)")
}

if task.result != nil {
print("Successfully uploaded!")

let credentialsProvider = AWSCognitoCredentialsProvider(regionType: CognitoRegionType, identityPoolId: CognitoIdentityPoolId)
let configuration = AWSServiceConfiguration(region: DefaultServiceRegionType, credentialsProvider:credentialsProvider)
let aws3 = AWSS3(configuration: configuration)
let publicURL = aws3.configuration.endpoint.URL.URLByAppendingPathComponent(uploadRequest.bucket!).URLByAppendingPathComponent(uploadRequest.key!)
print(publicURL)
}

return nil
}


This works well and I get proper the public URL.

https://s3-ap-northeast-1.amazonaws.com/myapp/DAEF70E9-495A-40B4-B853-3B337486185D-4988-00000E22AB8E25A6.jpg


I have two problems.

1). Initializing it this way
AWSS3(configuration: configuration)
is deprecated now.

2). This while initializing code already happens inside the App Delegate's
didFinishLaunchingWithOptions
method.

let credentialsProvider = AWSCognitoCredentialsProvider(regionType: CognitoRegionType, identityPoolId: CognitoIdentityPoolId)
let configuration = AWSServiceConfiguration(region: DefaultServiceRegionType, credentialsProvider:credentialsProvider)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration


However trying to call the
endpoint
property from this configuration returns nil.

So what I'm looking to do is this. I don't want to repeat the initializing code in both App Delegate and here. So if there's a way to get a reference to the already initialized object in App Delegate, I'd love to know.

Answer

I was actually able to get an instance of S3 object with AWSS3.defaultS3(). So I could construct the public URL like this.

let publicURL = AWSS3.defaultS3().configuration.endpoint.URL.URLByAppendingPathComponent(uploadRequest.bucket!).URLByAppendingPathComponent(uploadRequest.key!)