繁体   English   中英

如何在iOS上使用AWS上载图像时解决错误

[英]How to resolve an error when uploading an image with AWS on iOS

我正在按照本教程进行操作该教程涉及使用cognito将UIImage上传到s3存储桶进行身份验证。 我可以连接到cognito,因为我的设备显示在身份池中。 但是,当我尝试将图像上传到存储桶时,我收到此错误:

Error Domain=com.amazonaws.AWSGeneralErrorDomain Code=3 "The request signature we calculated does not match the signature you provided. Check your key and signing method." UserInfo=0x17dc0f40 {NSLocalizedDescription=The request signature we calculated does not match the signature you provided. Check your key and signing method.}

Cognito身份验证策略如下所示:

    {
"Version": "2012-10-17",
"Statement": [{
    "Action": [
        "mobileanalytics:PutEvents",
        "cognito-sync:*",
        "s3:*"
    ],
    "Effect": "Allow",
    "Resource": [
        "*"
    ]
}]
}

设置凭据的代码如下所示:

    AWSCognitoCredentialsProvider *credentialsProvider = [AWSCognitoCredentialsProvider
                                                      credentialsWithRegionType:AWSRegionUSEast1
                                                      accountId:@"#######"
                                                      identityPoolId:@"######"
                                                      unauthRoleArn:@"#####"
                                                      authRoleArn:@"######"];

AWSServiceConfiguration *configuration = [AWSServiceConfiguration configurationWithRegion:AWSRegionUSEast1
                                                                      credentialsProvider:credentialsProvider]

并且将图像上传到s3的代码如下所示:

    NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"image.png"];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:tempPath atomically:YES];


NSURL *url = [[NSURL alloc] initFileURLWithPath:tempPath];

AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
uploadRequest.bucket = @"##########";
//uploadRequest.ACL = AWSS3ObjectCannedACLPublicRead;
uploadRequest.key = @"image.png";
//uploadRequest.contentType = @"image/png";
uploadRequest.body = url;

uploadRequest.uploadProgress =^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend){
    dispatch_sync(dispatch_get_main_queue(), ^{

    });
};

AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];
[[transferManager upload:uploadRequest] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task) {
    if (task.error) {
        NSLog(@"%@", task.error);
    }else{
        //success
        NSLog(@"success");
        [[NSFileManager defaultManager] removeItemAtURL:url error:nil];
    }
    return nil;
}];

以下是亚马逊s3上传图片的代码,也包含一步一步的描述。

- (void)uploadToS3{
    // get the image from a UIImageView that is displaying the selected Image
    UIImage *img = _selectedImage.image;

    // create a local image that we can use to upload to s3
    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"image.png"];
    NSData *imageData = UIImagePNGRepresentation(img);
    [imageData writeToFile:path atomically:YES];

    // once the image is saved we can use the path to create a local fileurl
    NSURL *url = [[NSURL alloc] initFileURLWithPath:path];

    // next we set up the S3 upload request manager
    _uploadRequest = [AWSS3TransferManagerUploadRequest new];
    // set the bucket
    _uploadRequest.bucket = @"s3-demo-objectivec";
    // I want this image to be public to anyone to view it so I'm setting it to Public Read
    _uploadRequest.ACL = AWSS3ObjectCannedACLPublicRead;
    // set the image's name that will be used on the s3 server. I am also creating a folder to place the image in
    _uploadRequest.key = @"foldername/image.png";
    // set the content type
    _uploadRequest.contentType = @"image/png";
    // we will track progress through an AWSNetworkingUploadProgressBlock
    _uploadRequest.body = url;

    __weak ViewController *weakSelf = self;

    _uploadRequest.uploadProgress =^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend){
        dispatch_sync(dispatch_get_main_queue(), ^{
            weakSelf.amountUploaded = totalBytesSent;
            weakSelf.filesize = totalBytesExpectedToSend;
            [weakSelf update];

        });
    };

    // now the upload request is set up we can creat the transfermanger, the credentials are already set up in the app delegate
    AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];
    // start the upload
    [[transferManager upload:_uploadRequest] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task) {

        // once the uploadmanager finishes check if there were any errors
        if (task.error) {
            NSLog(@"%@", task.error);
        }else{// if there aren't any then the image is uploaded!
            // this is the url of the image we just uploaded
            NSLog(@"https://s3.amazonaws.com/s3-demo-objectivec/foldername/image.png");
        }

        return nil;
    }];

}

请参阅sledgedev博客的更多细节

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM