swift - 使用 Swift 3 和 Amazon SDK 显示图像上传到 Amazon S3 的上传进度

标签 swift file-upload amazon-s3 swift3 ios10

我能够成功地将图像上传到 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)

这是上传图片功能...

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)。他们都有 2 种不同的方法,最后一个链接我也无法正常工作。

我不确定我做错了什么。

最佳答案

好吧,我找到了问题的解决方案,显然我只是没有完全遵循。

这是我新修改的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
        })

    }

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

关于swift - 使用 Swift 3 和 Amazon SDK 显示图像上传到 Amazon S3 的上传进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41114991/

相关文章:

ios - socket 检测不工作时要检查什么?

ios - 获取 Assets 中声明的颜色的浅色或深色变体

ios - 在 UITableViewDelegate 扩展中使用未解析的标识符

python - 有没有一种简单的方法可以使列表表现为文件(使用 ftplib)

ruby-on-rails - Rails 4 + Devise + 回形针 + S3 示例?

ios - 当列数更改时 UICollectionView 崩溃

java - Android写入文件

javascript - 如何在 nativescript 中使用多部分表单数据上传文件?

architecture - Amazon S3 文件和路径命名架构决策

java - 在 aws elastic beanstalk 上上传文件?