Ios Amazon S3 Cognito-从图像选取器上载图像-Swift 3

Ios Amazon S3 Cognito-从图像选取器上载图像-Swift 3,ios,amazon-web-services,amazon-s3,swift3,uiimagepickercontroller,Ios,Amazon Web Services,Amazon S3,Swift3,Uiimagepickercontroller,我已经成功地将静态图像上传到AWS服务器。当我将它与imagepicker结合使用时,我面临一个wierd问题,因为同一个图像被上传到AWS,尽管我对它们进行了不同的选择和命名。代码如下: internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let image = info[UIImage

我已经成功地将静态图像上传到AWS服务器。当我将它与imagepicker结合使用时,我面临一个wierd问题,因为同一个图像被上传到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
 }
内部函数imagePickerController(\uPicker:UIImagePickerController,
didFinishPickingMediaWithInfo:[字符串:任意])
{
将image=info[UIImagePickerControllerOriginalImage]设为!UIImage
var imageUrl=info[UIImagePickerControllerReferenceURL]作为?NSURL
让imageName=imageUrl?.lastPathComponent
让documentDirectory=NSSearchPathForDirectoriesInDomains(.documentDirectory、.userDomainMask,true)。首先!
让photoURL=NSURL(fileURLWithPath:documentDirectory)
让localPath=photoURL.appendingPathComponent(imageName!)
打印(“图像名称:\(图像名称)”)
如果!FileManager.default.fileExists(atPath:localPath!.path){
做{
尝试UIImageJPEGRepresentation(图像,1.0)?。写入(到:localPath!)
打印(“文件已保存”)
//让imageData=NSData(contentsOf:localPath!)
//让finalURL=localPath!
//这是在swift 2中;以上两行在swift 3中是等效的。我认为问题就在这里
//让imageData=NSData(contentsOfFile:localPath)!
//imageURL=NSURL(fileURLWithPath:localPath)
}抓住{
打印(“保存文件时出错”)
}
}
否则{
打印(“文件已存在”)
}
self.disclose(动画:true,完成:nil)
let credentialProvider=AWSCognitoCredentialsProvider(区域类型:.USEast1,identityPoolId:“标识池id”)
let configuration=AWSServiceConfiguration(区域:.APSoutheast1,credentialProvider:credentialProvider)
AWSServiceManager.default().defaultServiceConfiguration=配置
//这些是我使用的静态值,它们对单独的图像非常有效
//让localFileName=“警报”\u bg
//让ext=“png”
//让remoteName=localFileName+“+ext
//让imageURL=Bundle.main.url(forResource:localFileName,扩展名:ext)!
让transferManager=AWSS3TransferManager.default()
让uploadRequest=AWSS3TransferManagerPloadRequest()!
uploadRequest.bucket=“bucket”
让imageAWSName=“ios_“+nsuid().uuiString+”.jpg
uploadRequest.key=imageAWSName
uploadRequest.body=localPath!作为URL
uploadRequest.contentType=“image/jpg”
打印(“请求123:\(上传请求)”)
uploadRequest.uploadProgress={(bytesSent,totalBytesSent,totalBytesExpectedToSend)->在中无效
DispatchQueue.main.async(执行:{
//self.amountupload=totalBytesSent//显示标签中的更新数据状态。
//self.fileSize=totalBytesExpectedToSend
打印(“进度:\(totalBytesSent)/\(totalBytesExpectedToSend)”)
})
}
transferManager.upload(uploadRequest).continueWith(执行器:AWSExecutor.mainThread(),block:{(任务:AWSTask和),但这些都在早期版本的swift中,我无法在swift 3中转换它,也无法将imagepicker与AWS正确组合。

请有人帮忙。

实际上,当你这样做时:

let photoURL          = NSURL(fileURLWithPath: documentDirectory)
let localPath         = photoURL.appendingPathComponent(imageName!)
您正在将localPath创建为
URL

因此,当您进行以下操作时:

let imageURL = NSURL(fileURLWithPath: localPath)
它给出了错误,因为localPath是
URL
而不是
String
。 在这里,您可以直接使用as:

let imageURL = localPath!

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

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)
让imageAWSName=“ios_“+nsuid().uuidString+”.jpg
将image=info[UIImagePickerControllerOriginalImage]设为!UIImage
让documentDirectory=NSSearchPathForDirectoriesInDomains(.documentDirectory、.userDomainMask,true)。首先!
让photoURL=NSURL(fileURLWithPath:documentDirectory)
让localPath=photoURL.appendingPathComponent(imageAWSName)
如果!FileManager.default.fileExists(atPath:localPath!.path){
做{
尝试UIImageJPEGRepresentation(图像,1.0)?。写入(到:localPath!)
打印(“文件已保存”)
}抓住{
打印(“保存文件时出错”)
}
}
否则{
打印(“文件已存在”)
}
让credentialProvider=AWSCognitoCredentialsProvider(regionType:.USEast1,identityPoolId:“您的身份池id”)
let configuration=AWSServiceConfiguration(区域:.APSoutheast1,credentialProvider:credentialProvider)
AWSServiceManager.default().defaultServiceConfiguration=配置
让transferManager=AWSS3TransferManager.default()
让uploadRequest=AWSS3TransferManagerPloadRequest()!
让您的bucket name=“您的bucket name”
uploadRequest.bucket=yourBucketName
uploadRequest.key=imageAWSName
uploadRequest.body=localPath!作为URL
uploadRequest.contentType=“image/jpg”
uploadRequest.uploadProgress={(bytesSent,totalBytesSent,totalBytesExpectedToSend)->在中无效
DispatchQueue.main.async(执行:{
//self.amountupload=totalBytesSent//显示标签中的更新数据状态。
//self.fileSize=totalBytesExpectedToSend
打印(“进度:\(totalBytesSent)/\(totalBytesExpectedToSend)”)
})
}
transferManager.upload(uploadRequest).continueWith(执行器:AWSExecutor.mainThread(),块:{(任务:AWSTask)->中的任何
如果let error=task.error{
打印(“上载失败,错误:(\(error.localizedDescription)))
}
如果task.result!=nil{
让s3URL=URL(字符串:https://s3-ap-southeast-1.amazonaws.com/\(你的BucketName)/\(imageAWSName)!
打印(“上载到:\(s3URL)”)
}
归零
})
self.picker.disclose(动画:true,完成:nil)
确保localPath中使用的imageAWSName始终与我所做的不同。这是最重要的,否则AWS将多次保存同一图像