Joseph Astrahan
Joseph Astrahan

Reputation: 9072

Upload Image to Amazon S3 Using Swift3

After looking around at different threads such as these (Swift - AWS S3 Upload Image from Photo Library and download it), and (Upload image AWS S3 bucket in swift), I got pretty close to getting an image upload to work but can't figure out what I'm doing wrong?

I get the following error below in my console.

Error: Error Domain=com.amazonaws.AWSS3TransferUtilityErrorDomain Code=1 "(null)" UserInfo={Server=AmazonS3, Transfer-Encoding=Identity, Connection=close, Content-Type=application/xml, Date=Tue, 13 Dec 2016 05:58:32 GMT, x-amz-request-id=2A76DF0FE33476C5, x-amz-id-2=QWZgOETbWQfddlqKmm0w3Z9HFGM2x1DWnrFjukiajTsIXfbSt9W0orTkoZeNXH/bI1xfc3mxI4Q=, x-amz-bucket-region=us-west-1}

My code is below:

let myIdentityPoolId = "us-west-2:dca2beb4-etcetcetc...."
                let credentialsProvider:AWSCognitoCredentialsProvider = AWSCognitoCredentialsProvider(regionType: AWSRegionType.usWest2, identityPoolId: myIdentityPoolId)
                let configuration = AWSServiceConfiguration(region: AWSRegionType.usWest2, credentialsProvider: credentialsProvider)
                AWSServiceManager.default().defaultServiceConfiguration = configuration

I then call to upload my image with a function I made below

func uploadImage(filename:String){
        print("AWS Upload Image Attempt...")
        //defining bucket and upload file name
        let S3BucketName: String = "distribution-tech-mobile"
        let filepath = "\(AppDelegate.appDelegate.applicationDocumentsDirectory())/\(filename)"
        let imageURL = URL(fileURLWithPath: filepath)
        let S3UploadKeyName = filename //TODO: Change this later

        let uploadRequest = AWSS3TransferManagerUploadRequest()
        uploadRequest?.bucket = S3BucketName
        uploadRequest?.key = filename
        uploadRequest?.contentType = "image/jpeg"
        uploadRequest?.body = imageURL
        uploadRequest?.serverSideEncryption = AWSS3ServerSideEncryption.awsKms
        uploadRequest?.uploadProgress = { (bytesSent, totalBytesSent, totalBytesExpectedToSend) -> Void in
            DispatchQueue.main.async(execute: {
                self.amountUploaded = totalBytesSent // To show the updating data status in label.
                self.fileSize = totalBytesExpectedToSend
                print("\(totalBytesSent)/\(totalBytesExpectedToSend)")
            })
        }

        self.uploadCompletionHandler = { (task, error) -> Void in
            DispatchQueue.main.async(execute: {
                if ((error) != nil){
                    print("Failed with error")
                    print("Error: \(error!)");
                }
                else{
                    print("Sucess")
                }
            })
        }

        let transferUtility = AWSS3TransferUtility.default()
        let expression = AWSS3TransferUtilityUploadExpression()

        transferUtility.uploadFile(imageURL, bucket: S3BucketName, key: S3UploadKeyName, contentType: "image/jpeg", expression: expression, completionHander: uploadCompletionHandler).continue({ (task) -> AnyObject! in
            if let error = task.error {
                print("Error: \(error.localizedDescription)")
            }
            if let exception = task.exception {
                print("Exception: \(exception.description)")
            }
            if let _ = task.result {
                print("Upload Starting!")
            }

            return nil;
        })

    }

I get the console message "Upload Starting" and then a message "Failed with error" (which comes from my completion handler), followed by the error I assume from Amazon.

Any thoughts on what I'm doing wrong?

Upvotes: 0

Views: 1818

Answers (1)

Joseph Astrahan
Joseph Astrahan

Reputation: 9072

Okay I found the answer, but I have a different problem now that I'll post in another question regarding showing upload progress.

The answer was my bucket was created in the incorrect region. I created my credentials in Oregon, which is Us-West-2, and I created the bucket in Northern California by accident the first time. This apparently created the error.

Upvotes: 1

Related Questions