简体   繁体   中英

How to upload image to AWS S3 in iOS?

I'm using an UIImagePicker to select or taking photos in my app. And after I selected the image, I need upload it to the AWS S3. I did the following steps,

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    self.imgView.image = chosenImage;
    imageUrl = info[UIImagePickerControllerReferenceURL];
    NSString * timestamp = TimeStamp;
    NSString *UUID = [[NSUUID UUID] UUIDString];

    fileName = [NSString stringWithFormat:@"posts/images/%@%@.jpg", UUID, timestamp];

    [picker dismissViewControllerAnimated:YES completion:NULL];

}

And, for uploading,

AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
uploadRequest.body = image;
uploadRequest.key = fileName;
uploadRequest.bucket = MY_BUCKET;
uploadRequest.ACL = AWSS3ObjectCannedACLPublicRead;
AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];

__weak BTEditProfileViewController *weakSelf = self;
[[transferManager upload:uploadRequest] continueWithBlock:^id(AWSTask *task) {
    if (task.error) {
        if ([task.error.domain isEqualToString:AWSS3TransferManagerErrorDomain]) {
            switch (task.error.code) {
                case AWSS3TransferManagerErrorCancelled:
                case AWSS3TransferManagerErrorPaused:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSLog(@"COMPLETED!!");
                    });
                }
                    break;

                default:
                    NSLog(@"Upload failed: [%@]", task.error);
                    break;
            }
        } else {
            NSLog(@"Upload failed: [%@]", task.error);
        }
    }

    if (task.result) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"RESULT:::%@",task.result);
        });
    }

    return nil;
}];

When I'm running this I got the following error.

Upload failed: [Error Domain=com.amazonaws.AWSS3TransferManagerErrorDomain Code=5 "'body' can not be nil" UserInfo={NSLocalizedDescription='body' can not be nil}]

How may I fix this?

The body property needs to be an instance of NSURL (needs to be a file URL).

Note that we are phasing out AWSS3TransferManager . AWSS3TransferUtility replaces AWSS3TransferManager and can upload an NSData , so you should take a look.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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