Swift iOS:无法将图像上传到AWS S3

时间:2019-09-23 08:04:37

标签: ios swift amazon-web-services amazon-s3

因此,我使用以下策略创建了一个S3存储桶:

{
    "Version": "2012-10-17",
    "Id": "Policy123",
    "Statement": [
        {
            "Sid": "Stmt123",
            "Effect": "Allow",
            "Principal": {
                "AWS": "User_ARN"
            },
            "Action": "s3:ListBucket",
            "Resource": "Buckent_ARN"
        },
        {
            "Sid": "Stmt1569218242333",
            "Effect": "Allow",
            "Principal": {
                "AWS": "User_ARN"
            },
            "Action": [
                "s3:DeleteObject",
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": "Buckent_ARN/*"
        }
    ]
}

我还创建了一个Cognito身份池和一个IAM用户。现在,我正在尝试将图像从我的应用上传到存储桶中,并得到: 该操作无法完成。 (com.amazonaws.AWSS3TransferUtilityErrorDomain错误2。)

在我的AppDelegate中,我设置了以下内容:

 let credentialsProvider = AWSCognitoCredentialsProvider(regionType:.usWest2,
           identityPoolId:"us-west-2:XXXXX")

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

        AWSServiceManager.default().defaultServiceConfiguration = configuration

并尝试这样上传我的图片:

if let imageToUpload =  self.myImage {
    let awsTransferUtilitytransferUtility = AWSS3TransferUtility.default()
    let s3BucketName = "my-bucket"

    let pngImage = imageToUpload.pngData()
    let filename = "someImage.png"
    let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(filename)
    do {
        try pngImage?.write(to: fileURL)

        awsTransferUtilitytransferUtility.uploadData(pngImage!, bucket: s3BucketName, key: filename, contentType: "img/png", expression: nil) { (uploadTask, error) in
            if error != nil {
                print("error is: \(error!.localizedDescription)")
            } else {
                print("Task Result: \(uploadTask)")
            }
        }

    } catch {
        print("File not saved!")
    }
}

我非常确定这是一个权限问题,因为我创建了一个公共存储桶,并且能够顺利上传图像。我是AWS的新手,权限让我非常困惑。我创建了一个IAM角色,将其分配给存储桶策略,并设置了一个Cognito身份池。但是,Cognito和IAM之间有什么联系?我需要在代码中提供IAM凭据才能上传吗?我完成了以下文章的设置:https://medium.com/@haydnjmorris/uploading-photos-to-aws-s3-getting-started-with-cognito-and-iam-c96ba5b5496d

任何帮助将不胜感激!

0 个答案:

没有答案