首先,要将文件、图像、视频上传到 AWS S3 privet 存储桶,您需要对从后端服务器获得的所需的(' CognitoId、CognitoAccesstoken )进行AWS 身份验证。你应该有 ' CognitoPoolID '、' S3存储桶名称' 和 ' Region ' 您可以将它们保存在 swift 代码中的常量文件中。之后,您必须为 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)
}
}
//从您上传文件的类中编写以下代码
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;
}
}