尝试使用方法 (AWSS3TransferUtility) 将音频上传到 AWS S3 存储桶。吊舱-AWSS3

Trying to upload audio to AWS S3 bucket using method(AWSS3TransferUtility). Pod - AWSS3

我们正在尝试使用方法 (AWSS3TransferUtility) 将音频上传到 AWS S3 存储桶。吊舱-AWSS3。我们低于错误。

错误描述:

Error Domain=com.amazonaws.AWSS3TransferUtilityErrorDomain Code=2 "(null)" UserInfo={Server=AmazonS3, Transfer-Encoding=Identity, Connection=close, Content-Type=application/xml, Date=Fri, 06 Sep 2021 04:43:50 GMT, x-amz-request-id=VH53PCCWA529FDRC, x-amz-id-2=4uZoqJj+TJ93WUBSnrC889CAj3gkGGw/V6iJjhrVjB2+ZygTflGcPAV+amfxmeBGeGHHVXv3nHk=}

func uploadFile(withImage image: UIImage) {

    let credentialsProvider = AWSCognitoCredentialsProvider(regionType:AWSRegionType.USEast2,

                                                            identityPoolId:"us-east-2:fe41c293-df49-49a4-886d-094f2cd8d0fd")

    let configuration = AWSServiceConfiguration(region:.USEast2, credentialsProvider:credentialsProvider)

    let tuConf = AWSS3TransferUtilityConfiguration()

    AWSS3TransferUtility.register(

        with: configuration!,

        transferUtilityConfiguration: tuConf,

        forKey: "transfer-utility-with-advanced-options"

    )

    let transferUtility = AWSS3TransferUtility.s3TransferUtility(forKey: "transfer-utility-with-advanced-options")

    AWSServiceManager.default().defaultServiceConfiguration = configuration

    let s3BucketName = "testingimageupload"

    let data: Data = image.pngData()!

    let remoteName = generateRandomStringWithLength(length: 12)+"."+"png"

    print("REMOTE NAME : ",remoteName)

    let expression = AWSS3TransferUtilityUploadExpression()

    expression.setValue("public-read", forRequestHeader: "x-amz-acl")

    expression.progressBlock = { (task, progress) in

        DispatchQueue.main.async(execute: {

            // Update a progress bar

        })

    }

    var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?

    completionHandler = { (task, error) -> Void in

        DispatchQueue.main.async(execute: {

            

        })

    }

    transferUtility!.uploadData(data, bucket: s3BucketName, key: "private/Abhay/" + remoteName, contentType: "image/"+"png", expression: expression, completionHandler: completionHandler).continueWith { (task) -> Any? in

        if let error = task.error {

            print("Error : \(error.localizedDescription)")

        }

        

        if task.result != nil {

            let url = AWSS3.default().configuration.endpoint.url

            let publicURL = url?.appendingPathComponent(s3BucketName).appendingPathComponent(remoteName)

            if let absoluteString = publicURL?.absoluteString {

                // Set image with URL

                print("Image URL : ",absoluteString)

            }

        }

        return nil

    }

先决条件:设置 AWS Amplify CLI。

1。项目初始化。


amplify init:在本地和远程设置 AWS Amplify。

注意:未找到放大初始化命令

1)`npm install -g @aws-amplify/cli` - ### install the Amplify CLI ###
2)`curl -sL https://aws-amplify.github.io/amplify-cli/install | bash && $SHELL` ### configured $Path correctly ###
3)`amplify init` ###Try Amplify init###

Amplify Demo project or click enter for the default name : 输入项目名称

Dev or click enter for the default name : 输入环境名称

Choose Visual Studio Code : 选择默认编辑器

iOS : 选择您正在构建的应用类型

yes : 您要使用 AWS 配置文件吗?

2。项目存储设置

amplify add storage : 添加存储空间

Content(Images, audio, video, etc.) : Select 下面提到的服务

yes : (Amazon Cognito) 你现在要添加授权吗?

No:是否要配置高级设置?

bucket name or click enter for the default name : 请提供存储桶名称

Auth users only or Auth and guest users:谁应该有访问权限

create/update , read , delete. : 您希望经过身份验证的用户获得什么样的访问权限?

create/update , read , delete.:您希望来宾用户拥有何种访问权限?

No : 你想为你的 S3 Bucket 添加一个 lama 触发器吗?

3。推送 - 将配置放大到后端

amplify push:放大推送

Yes:您确定要继续吗?

Pod 安装

target ‘ProjectName do
  use_frameworks!
  pod 'Amplify'
  pod 'AmplifyPlugins/AWSS3StoragePlugin'
  pod 'AmplifyPlugins/AWSCognitoAuthPlugin'
end

代码:ViewController.swift

import Amplify
import AmplifyPlugins

func configureAmplify() {
        do {
            try Amplify.add(plugin: AWSCognitoAuthPlugin())
            try Amplify.add(plugin: AWSS3StoragePlugin())
            try Amplify.configure()
            print("Successfully configured Amplify")
        } catch  {
            print("Could not configure Amplify", error)
        }
    }
func uploadFile() {
        let audioUrl = URL(string: "/Users/appaiah/Downloads/RealAudio.mp3")!
        Amplify.Storage.uploadFile(key: fileKey, local: audioUrl){          // let fileKey = "SampleAudio.mp3"
            result in
            switch result {
            case .success(let key):
                print("file with key uploaded \(key)")
            case .failure(let error):
                print("failed \(error)")
            }
        }
    }


func downloadFile(){
                    let downloadToFileName = getTermsOfUseURL()     
                    Amplify.Storage.downloadFile(
                        key: fileKey,
                        local: downloadToFileName,
                        progressListener: { progress in
                            print("Progress: \(progress)")
                        }, resultListener: { event in
                            switch event {
                            case .success:
                                print("Completed")
                                DispatchQueue.main.async {  }
                            case .failure(let storageError):
                                print("Failed: \(storageError.errorDescription). \(storageError.recoverySuggestion)")
                            }
                        })
                }
    func getTermsOfUseURL() -> URL {
            let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            print(paths[0].appendingPathComponent(fileKey))
            return paths[0].appendingPathComponent(fileKey)
        }