0

我已经成功将静态图像上传到AWS服务器。当我将它与imagepicker结合使用时,我面临着一个奇怪的问题,因为即使我选择并命名它们,也会将相同的图像上传到AWS。代码如下:Amazon S3 Cognito - 从图像选择器上传图像 - Swift 3

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,但这些都是在早期版本的迅速和我无法将其转换斯威夫特3与AWS适当地组合imagepicker。 有人请帮忙。

回答

1

我找到了解决我的问题:

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即使从拾取器中选取不同的图像,也会多次保存相同的图像。

希望它有助于未来的人!

0

其实,当你这样做:

let photoURL   = NSURL(fileURLWithPath: documentDirectory) 
let localPath   = photoURL.appendingPathComponent(imageName!) 

您创建了localPath为URL
所以,当你正在做的:

let imageURL = NSURL(fileURLWithPath: localPath) 

它给错误的,因为是localPath为不URLString。 在这里,你可以直接使用如:

let imageURL = localPath! 
+0

所以你的意思是说我可以直接使用localPath?我不需要再次形成URL? – Mamta

+0

是的,这将解决你的'不能转换价值...'错误 – D4ttatraya

+0

好的。我删除了这两行。将静态AWS代码与图像选择器结合仍然面临问题。你能帮助我吗? – Mamta