簡體   English   中英

Amazon S3 Cognito-從圖像選擇器上傳圖像-Swift 3

[英]Amazon S3 Cognito - Upload image from image picker - Swift 3

我已成功將靜態圖像上傳到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
 }

我看到很多博客如這個這個 ,但這些都是在早期版本的迅速和我無法將其轉換斯威夫特3與AWS適當地組合imagepicker。 有人請幫忙。

我找到了解決問題的方法:

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也會多次保存同一圖像。

希望以后能對某人有所幫助!

實際上,當您這樣做時:

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

您正在將localPath創建為URL
因此,當您執行以下操作時:

let imageURL = NSURL(fileURLWithPath: localPath)

這是錯誤的,因為localPath是URL而不是String 在這里您可以直接使用as:

let imageURL = localPath!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM