【问题标题】:Show Upload Progress for Image Upload to Amazon S3 using Swift 3 and Amazon SDK显示使用 Swift 3 和 Amazon SDK 将图像上传到 Amazon S3 的上传进度
【发布时间】:2017-04-28 03:41:02
【问题描述】:

我能够成功地将图像上传到 Amazon S3,但我似乎不知道如何显示这样做的进度。

我目前正在上传。

import UIKit
import MapKit
import CoreData
import AWSCore
import AWSCognito
import AWSS3
import MobileCoreServices
import AWSMobileAnalytics

在我的上传按钮中,我有以下代码...

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

self.uploadImage(filename)

这是uploadImage函数……

func uploadImage(filename:String){
        print("AWS Upload Image Attempt...")
        //defining bucket and upload file name
        let S3BucketName: String = "distribution-tech-mobile-live"
        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;
        })

    }

我从另一个线程获得了图像上传进度的代码,但那里的解决方案似乎不起作用或者我误解了它。

Upload image AWS S3 bucket in swift,以及这个线程 (Swift - AWS S3 Upload Image from Photo Library and download it)。他们都有两种不同的方法,最后一个链接我也无法使用。

我不确定自己做错了什么。

【问题讨论】:

  • 问题出在哪里?您有 .uploadProgress 闭包,它为您提供上传进度,您甚至可以在代码中使用它。在UI中添加一些代码更新进度就完成了。
  • 我混合和匹配两种不同的上传方法的问题,所以我以前用不同的方式进行上传进度,并使用另一种方式触发上传,所以上传进度永远不会起作用。由于有关此主题的答案的所有变体,我感到困惑。

标签: swift file-upload amazon-s3 swift3 ios10


【解决方案1】:

好的,我找到了问题的解决方案,显然我只是没有坚持到底。​​p>

这是我新修改的uploadImage函数

func uploadImage(filename:String){
        print("AWS Upload Image Attempt...")
        //defining bucket and upload file name
        let S3BucketName: String = "distribution-tech-mobile-live"
        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 = S3UploadKeyName
        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)")
            })
        }

        let transferManager = AWSS3TransferManager.default()
        transferManager?.upload(uploadRequest).continue(with: AWSExecutor.mainThread(), withSuccessBlock: { (taskk: AWSTask) -> Any? in
            if taskk.error != nil {
                // Error.
                print("error")
            } else {
                // Do something with your result.
                print("something with result when its done")
            }
            return nil
        })

    }

这在结果完成时和上传过程中都有位置,并且更有意义。

【讨论】:

  • 您能否展示如何从 imagepicker 中选择图像并生成 URL 并通过与上述相同的方法发送到 AWS。几个小时以来我一直坚持这一点
  • 当然这很容易,一旦我进入办公室,我们可以在这里开始聊天
  • 我正在使用这种方法来显示 AWS 上传进度。但是媒体没有在 S3 上上传。该方法显示上传进度并成功完成。当我在 S3 上检查图像时,我们无法找到它。
  • AWSS3TransferManager 已弃用
猜你喜欢
  • 1970-01-01
  • 2020-10-02
  • 1970-01-01
  • 2017-04-28
  • 2013-11-21
  • 2012-02-14
  • 2012-12-20
  • 2017-10-30
  • 1970-01-01
相关资源
最近更新 更多