First of all for uploading file, image,video to AWS S3 privet bucket, you need to do AWS authentication for the that you need ('CognitoId, CognitoAccesstoken) which you get from backend-server.You should have 'CognitoPoolID', 'S3 bucket name' and 'Region' which you can save in Constant file inside swift code.
After that you have to write separate class for AWS Authentication
import UIKit
import AWSCore
// this custom class is dedicated for getting getting aws dev auth identity credentials
class DeveloperAuthenticatedIdentityProvider: AWSCognitoCredentialsProviderHelper {
override init(regionType: AWSRegionType, identityPoolId: String, useEnhancedFlow: Bool, identityProviderManager: AWSIdentityProviderManager?) {
super.init(regionType: regionType, identityPoolId: identityPoolId, useEnhancedFlow: useEnhancedFlow, identityProviderManager: identityProviderManager)
}
override func token() -> AWSTask<NSString> {
self.identityId = “ADD_COGNITO_IDENTITY_ID”
let token = “ADD_COGNITO_ACCESS_TOKEN”
return AWSTask(result: token )
}
override func logins () -> AWSTask<NSDictionary> {
return super.logins()
}
/*
* Use the refresh method to communicate with your backend to get an
* identityId and token.
*/
func refresh() -> AWSTask<NSString> {
self.identityId = “ADD_COGNITO_IDENTITY_ID”
return AWSTask(result: identityID)
}
}
//Write below code from class from where you are uploading file
let devAuth = DeveloperAuthenticatedIdentityProvider.init(
regionType: ADD_REGION,
identityPoolId:”ADD_COGNITO_POOL_ID”,
useEnhancedFlow: true,
identityProviderManager: nil)
let credentialsProvider = AWSCognitoCredentialsProvider.init(regionType:”ADD_REGION”, identityProvider: devAuth)
let configuration = AWSServiceConfiguration.init(region:”ADD_REGION”, credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
@IBAction func uplaodVideo(){
uploadFile(with: "FILE_NAME", type: "mov")
}
func uploadFile(with resource: String, type: String) {
let key = "\(resource).\(type)"
let localImagePath = Bundle.main.path(forResource: resource, ofType: type)
let localImageUrl = URL(fileURLWithPath: localImagePath!)
let transferManager1 = AWSS3TransferUtility.default()
let expression = AWSS3TransferUtilityUploadExpression()
self.uploadCompletionHandler = { (task, error) -> Void in
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
if ((error) != nil){
print("Failed with error")
print("Error: \(error!)");
}
else{
print("Sucess")
}
})
}
let transferUtility = AWSS3TransferUtility.default()
transferUtility.uploadFile(localImageUrl, bucket: "", key: key, contentType: "video/mov", expression: expression, completionHandler: uploadCompletionHandler).continueWith { (task) -> AnyObject? in
if let error = task.error {
print("Error: \(error.localizedDescription)")
}
if let _ = task.result {
print("Upload Starting!")
}
return nil;
}
}