从iOS将多个图像上传到S3的有效方法

Dav*_*zov 2 amazon-s3 amazon-web-services ios

我在应用程序中将Amazon S3用作文件存储系统。我所有的item对象都有几个与之关联的图像,并且每个对象仅存储图像URL,以保持数据库的轻量化。因此,我需要一种有效的方法直接从iOS将多个图像上传到S3,并在成功完成后将它们的URL存储在我发送给服务器的对象中。我仔细研究了Amazon提供的SDK和示例应用程序,但是我遇到的唯一示例是单个图像上传,操作如下:

 func uploadData(data: NSData) {
    let expression = AWSS3TransferUtilityUploadExpression()
    expression.progressBlock = progressBlock

    let transferUtility = AWSS3TransferUtility.defaultS3TransferUtility()

    transferUtility.uploadData(
        data,
        bucket: S3BucketName,
        key: S3UploadKeyName,
        contentType: "text/plain",
        expression: expression,
        completionHander: completionHandler).continueWithBlock { (task) -> AnyObject! in
            if let error = task.error {
                NSLog("Error: %@",error.localizedDescription);
                self.statusLabel.text = "Failed"
            }
            if let exception = task.exception {
                NSLog("Exception: %@",exception.description);
                self.statusLabel.text = "Failed"
            }
            if let _ = task.result {
                self.statusLabel.text = "Generating Upload File"
                NSLog("Upload Starting!")
                // Do something with uploadTask.
            }

            return nil;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于5张以上的图片,这将成为一团糟,因为我必须等待每次上传成功返回后才能启动下一个,然后最终将对象发送到我的数据库。我是否需要有效,干净的代码来实现自己的目标?

亚马逊示例应用程序github的URL:https : //github.com/awslabs/aws-sdk-ios-samples/tree/master/S3TransferUtility-Sample/Swift

Bon*_*nke 5

这是我用来同时将多个图像上传到S3的代码DispatchGroup()

func uploadOfferImagesToS3() {
    let group = DispatchGroup()

    for (index, image) in arrOfImages.enumerated() {
        group.enter()

        Utils.saveImageToTemporaryDirectory(image: image, completionHandler: { (url, imgScalled) in
            if let urlImagePath = url,
                let uploadRequest = AWSS3TransferManagerUploadRequest() {
                uploadRequest.body          = urlImagePath
                uploadRequest.key           = ProcessInfo.processInfo.globallyUniqueString + "." + "png"
                uploadRequest.bucket        = Constants.AWS_S3.Image
                uploadRequest.contentType   = "image/" + "png"
                uploadRequest.uploadProgress = {(bytesSent:Int64, totalBytesSent:Int64, totalBytesExpectedToSend:Int64) in
                    let uploadProgress = Float(Double(totalBytesSent)/Double(totalBytesExpectedToSend))

                    print("uploading image \(index) of \(arrOfImages.count) = \(uploadProgress)")

                    //self.delegate?.amazonManager_uploadWithProgress(fProgress: uploadProgress)
                }

                self.uploadImageStatus      = .inProgress

                AWSS3TransferManager.default()
                    .upload(uploadRequest)
                    .continueWith(executor: AWSExecutor.immediate(), block: { (task) -> Any? in

                        group.leave()

                        if let error = task.error {
                            print("\n\n=======================================")
                            print("? Upload image failed with error: (\(error.localizedDescription))")
                            print("=======================================\n\n")

                            self.uploadImageStatus = .failed
                            self.delegate?.amazonManager_uploadWithFail()

                            return nil
                        }

                        //=>    Task completed successfully
                        let imgS3URL = Constants.AWS_S3.BucketPath + Constants.AWS_S3.Image + "/" + uploadRequest.key!
                        print("imgS3url = \(imgS3URL)")
                        NewOfferManager.shared.arrUrlsImagesNewOffer.append(imgS3URL)

                        self.uploadImageStatus = .completed
                        self.delegate?.amazonManager_uploadWithSuccess(strS3ObjUrl: imgS3URL, imgSelected: imgScalled)

                        return nil
                    })
            }
            else {
                print(" Unable to save image to NSTemporaryDirectory")
            }
        })
    }

    group.notify(queue: DispatchQueue.global(qos: .background)) {
        print("All \(arrOfImages.count) network reqeusts completed")
    }
}
Run Code Online (Sandbox Code Playgroud)

这是关键部分,我至少损失了5个小时。NSTemporaryDirectory 每个图片的 URL都必须不同

class func saveImageToTemporaryDirectory(image: UIImage, completionHandler: @escaping (_ url: URL?, _ imgScalled: UIImage) -> Void) {
    let imgScalled              = ClaimitUtils.scaleImageDown(image)
    let data                    = UIImagePNGRepresentation(imgScalled)

    let randomPath = "offerImage" + String.random(ofLength: 5)

    let urlImgOfferDir = URL(fileURLWithPath: NSTemporaryDirectory().appending(randomPath))
    do {
        try data?.write(to: urlImgOfferDir)
        completionHandler(urlImgOfferDir, imgScalled)
    }
    catch (let error) {
        print(error)
        completionHandler(nil, imgScalled)
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助!


Saf*_*ive 3

正如我在 H. Al-Amri 的回复中所说,如果您需要知道上次上传何时完成,您不能简单地迭代一组数据并一次上传所有数据。

在 Javascript 中,有一个库(我认为是 Async.js),可以轻松地对数组的各个元素进行后台操作,并在每个元素完成时以及整个数组完成时获取回调。由于我不知道 Swift 是否有类似的情况,因此您认为必须链接上传的直觉是正确的。

正如 @DavidTamrazov 在评论中解释的那样,您可以使用递归将调用链接在一起。我解决这个问题的方法有点复杂,因为我的网络操作是使用 NSOperationQueue 来链接 NSOperations 完成的。我将图像数组传递给自定义 NSOperation,该 NSOperation 上传该数组中的第一张图像。完成后,它会向我的 NSOperationsQueue 添加另一个 NSOperation 以及剩余图像的数组。当数组中的图像用完时,我知道我已经完成了。

以下是我从使用的大得多的块中切出的示例。将其视为伪代码,因为我对它进行了大量编辑,甚至没有时间编译它。但希望框架对于如何使用 NSOperations 做到这一点足够清楚。

class NetworkOp : Operation {
    var isRunning = false

    override var isAsynchronous: Bool {
        get {
            return true
        }
    }

    override var isConcurrent: Bool {
        get {
            return true
        }
    }

    override var isExecuting: Bool {
        get {
            return isRunning
        }
    }

    override var isFinished: Bool {
        get {
            return !isRunning
        }
    }

    override func start() {
        if self.checkCancel() {
            return
        }
        self.willChangeValue(forKey: "isExecuting")
        self.isRunning = true
        self.didChangeValue(forKey: "isExecuting")
        main()
    }

    func complete() {
        self.willChangeValue(forKey: "isFinished")
        self.willChangeValue(forKey: "isExecuting")
        self.isRunning = false
        self.didChangeValue(forKey: "isFinished")
        self.didChangeValue(forKey: "isExecuting")
        print( "Completed net op: \(self.className)")
    }

    // Always resubmit if we get canceled before completion
    func checkCancel() -> Bool {
        if self.isCancelled {
            self.retry()
            self.complete()
        }
        return self.isCancelled
    }

    func retry() {
        // Create a new NetworkOp to match and resubmit since we can't reuse existing.
    }

    func success() {
        // Success means reset delay
        NetOpsQueueMgr.shared.resetRetryIncrement()
    }
}

class ImagesUploadOp : NetworkOp {
    var imageList : [PhotoFileListMap]

    init(imageList : [UIImage]) {
        self.imageList = imageList
    }

    override func main() {
        print( "Photos upload starting")
        if self.checkCancel() {
            return
        }

        // Pop image off front of array
        let image = imageList.remove(at: 0)

        // Now call function that uses AWS to upload image, mine does save to file first, then passes
        // an error message on completion if it failed, nil if it succceeded
        ServerMgr.shared.uploadImage(image: image, completion: {  errorMessage ) in
            if let error = errorMessage {
                print("Failed to upload file - " + error)
                self.retry()
            } else {
                print("Uploaded file")
                if !self.isCancelled {
                    if self.imageList.count == 0 {
                        // All images done, here you could call a final completion handler or somthing.
                    } else {
                        // More images left to do, let's put another Operation on the barbie:)
                        NetOpsQueueMgr.shared.submitOp(netOp: ImagesUploadOp(imageList: self.imageList))
                    }
                }
            }
            self.complete()
         })
    }

    override func retry() {
        NetOpsQueueMgr.shared.retryOpWithDelay(op: ImagesUploadOp(form: self.form, imageList: self.imageList))
    }
}


// MARK: NetOpsQueueMgr  -------------------------------------------------------------------------------

class NetOpsQueueMgr {
    static let shared = NetOpsQueueMgr()

    lazy var opsQueue :OperationQueue = {
        var queue = OperationQueue()
        queue.name = "myQueName"
        queue.maxConcurrentOperationCount = 1
        return queue
    }()

    func submitOp(netOp : NetworkOp) {
         opsQueue.addOperation(netOp)
    }

   func uploadImages(imageList : [UIImage]) {
        let imagesOp = ImagesUploadOp(form: form, imageList: imageList)
        self.submitOp(netOp: imagesOp)
    }
}
Run Code Online (Sandbox Code Playgroud)