ios - Amazon S3 Cognito - 从图像选择器上传图像 - Swift 3

标签 ios amazon-web-services amazon-s3 swift3 uiimagepickercontroller

我已成功将静态图像上传到 AWS 服务器。当我将它与 imagepicker 结合使用时,我遇到了一个奇怪的问题,因为即使我以不同的方式选择和命名它们,但仍将相同的图像上传到 AWS。代码如下:

internal func imagePickerController(_ picker: UIImagePickerController,
 didFinishPickingMediaWithInfo info: [String : Any])
 {
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    var imageUrl          = info[UIImagePickerControllerReferenceURL] as? NSURL
    let imageName         = imageUrl?.lastPathComponent
    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    let photoURL          = NSURL(fileURLWithPath: documentDirectory)
    let localPath         = photoURL.appendingPathComponent(imageName!)

    print("image name : \(imageName)")

    if !FileManager.default.fileExists(atPath: localPath!.path) {
        do {
            try UIImageJPEGRepresentation(image, 1.0)?.write(to: localPath!)
            print("file saved")
            //let imageData = NSData(contentsOf: localPath!)
            //let finalURL = localPath!

            //this is in swift 2; above 2 lines are its equivalent in swift3. I think the problem lies here
            //let imageData = NSData(contentsOfFile: localPath)!
            //imageURL = NSURL(fileURLWithPath: localPath)

        }catch {
            print("error saving file")
        }
    }
    else {
        print("file already exists")
    }

    self.dismiss(animated: true, completion: nil)

    let credentialProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: "identity pool id")
    let configuration = AWSServiceConfiguration(region: .APSoutheast1, credentialsProvider: credentialProvider)
    AWSServiceManager.default().defaultServiceConfiguration = configuration

    //these are the static values I used that worked perfectly fine with separate images
    //let localFileName = "Alerts_bg"
    //let ext = "png"
    //let remoteName = localFileName + "." + ext
    //let imageURL = Bundle.main.url(forResource: localFileName, withExtension: ext)!

    let transferManager = AWSS3TransferManager.default()

    let uploadRequest = AWSS3TransferManagerUploadRequest()!
    uploadRequest.bucket = "bucket"
    let imageAWSName = "ios_" + NSUUID().uuidString + ".jpg"
    uploadRequest.key = imageAWSName
    uploadRequest.body = localPath! as URL
    uploadRequest.contentType = "image/jpg"

    print("req123 : \(uploadRequest)")

    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("progress : \(totalBytesSent)/\(totalBytesExpectedToSend)")
        })
    }

    transferManager.upload(uploadRequest).continueWith(executor: AWSExecutor.mainThread(), block: { (task:AWSTask<AnyObject>) -> Any? in
        if let error = task.error {
            print("Upload failed with error: (\(error.localizedDescription))")
        }
        if task.result != nil {

            let s3URL = URL(string: "https://s3-ap-southeast-1.amazonaws.com/bucket/\(imageAWSName)")!
            print("Uploaded to:\(s3URL)")
        }
        return nil
    })

 dismiss(animated:true, completion: nil) //5
 }

我看过很多博客,例如 thisthis但这些在早期版本的 swift 中,我无法在 Swift 3 中转换它并将 imagepicker 与 AWS 正确结合。 有人请帮忙。

最佳答案

我找到了解决问题的办法:

let imageAWSName = "ios_" + NSUUID().uuidString + ".jpg"

    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    let photoURL          = NSURL(fileURLWithPath: documentDirectory)
    let localPath         = photoURL.appendingPathComponent(imageAWSName)

    if !FileManager.default.fileExists(atPath: localPath!.path) {
        do {
            try UIImageJPEGRepresentation(image, 1.0)?.write(to: localPath!)
            print("file saved")
        }catch {
            print("error saving file")
        }
    }
    else {
        print("file already exists")
    }

    let credentialProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: “your identity pool id”)
    let configuration = AWSServiceConfiguration(region: .APSoutheast1, credentialsProvider: credentialProvider)
    AWSServiceManager.default().defaultServiceConfiguration = configuration

    let transferManager = AWSS3TransferManager.default()

    let uploadRequest = AWSS3TransferManagerUploadRequest()!
    let yourBucketName = “your bucket name”
    uploadRequest.bucket = yourBucketName

    uploadRequest.key = imageAWSName
    uploadRequest.body = localPath! as URL
    uploadRequest.contentType = "image/jpg"

    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("progress : \(totalBytesSent)/\(totalBytesExpectedToSend)")
        })
    }

    transferManager.upload(uploadRequest).continueWith(executor: AWSExecutor.mainThread(), block: { (task:AWSTask<AnyObject>) -> Any? in
        if let error = task.error {
            print("Upload failed with error: (\(error.localizedDescription))")
        }
        if task.result != nil {

            let s3URL = URL(string: "https://s3-ap-southeast-1.amazonaws.com/\(yourBucketName)/\(imageAWSName)")!
            print("Uploaded to:\(s3URL)")
        }
        return nil
    })

    self.picker.dismiss(animated: true, completion: nil)

确保在 localPath 中使用的 imageAWSName 始终与我所做的不同。这是最主要的事情,否则即使您从选择器中选择不同的图像,AWS 也会多次保存相同的图像。

希望它对以后的人有所帮助!

关于ios - Amazon S3 Cognito - 从图像选择器上传图像 - Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44255317/

相关文章:

ios - 设置SIAlertView的宽度

amazon-web-services - CloudFormation 模板失败并出现错误 "Service: AmazonEC2; Status Code: 400; Error Code: Unsupported"

java - 玩2.3.x : Non-blocking image upload to Amazon S3

python - 在 Heroku 上使用 Boto 时,无法连接到名称中带有句点的 S3 存储桶

ios - TabBarController 中的 UIImagePickerController

ios - 使用 SWIFT 将 indexPath.row 传递给自定义单元格中的按钮

iphone - 在不撤消旋转变换的情况下无法撤消缩放变换

amazon-web-services - Elastic beanstalk 实例无法访问私有(private) S3 文件

node.js - 限制对 AWS SQL Server 实例的外部访问

amazon-s3 - Hadoop 输入文件