使用swift将多个图像上传到Bucket AWS S3

时间:2018-01-18 13:33:35

标签: ios amazon-s3 file-upload

我正在尝试使用以下代码将图像上传到存储桶AWS s3。

    let ext = "jpeg"
    let uploadRequest = AWSS3TransferManagerUploadRequest()
    uploadRequest?.acl = .publicRead
    uploadRequest?.body = URL(fileURLWithPath: path)
    uploadRequest?.key = s3BucketKey
    uploadRequest?.bucket = S3BucketName
    uploadRequest?.contentType = "image/" + ext
    DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
        let transferManager = AWSS3TransferManager.default()
        transferManager.upload(uploadRequest!).continueWith { (task) -> AnyObject! in
            if let error = task.error {
                print("Upload failed ❌ (\(error))")
            }
            if task.result != nil {
                let s3URL = "http://s3.amazonaws.com/\(S3BucketName)/\(String(describing: uploadRequest!.key!))"
                print("Uploaded to:\n\(s3URL)")
                completion(s3URL)
            }
            else {
                print("Unexpected empty result.")
                completion(nil)
            }
            return nil
        }
    }

但是现在我需要将多个图像上传到存储桶AWS S3,我想在循环中使用相同的功能来上传文件,但需要花费更多的处理时间,我还需要在所有图像上传后同步我的数据。

请建议解决方法,这样可以减少上传多张图片的处理时间,我会在上传所有图片后收到通知。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用RxSwift框架。像...

// Multiple image uploading
RRAWSRxUpload.upload(dataList: [AWSImageData(type: .image1, image: #imageLiteral(resourceName: "image1")), AWSImageData(type: .image2, image: #imageLiteral(resourceName: "image2"))])
.subscribeOn(ConcurrentDispatchQueueScheduler.init(qos: .background))
.observeOn(MainScheduler.instance)
.subscribe(onNext: { response in
    print(response)
    //Get here all file uploaded key names after that you will call your server API call to update those files.
}, onError: { error in
    print(error.localizedDescription)
}).disposed(by: rxbag)

此外,了解有关RRAWSRXUpload的GitHub演示的更多信息。

您还可以使用Alamofire库通过RxSwift调用服务器API。

完成部分AWS S3上传后,您将通过RRAlamofireRxAPI调用服务器Alamofire API请求。

RRAWSRxUpload.upload(dataList: [AWSImageData(type: .image1, image: #imageLiteral(resourceName: "image1")), AWSImageData(type: .image2, image: #imageLiteral(resourceName: "image2"))])
        .flatMap { (keys) -> Observable<DataModelObject> in
            print(keys)// pass your files array/model to your server as parameters
            return RRAPIRxManager.rxCall(apiUrl: APIEndPoint.Name.uploadAWSImage, httpMethod: .post, param: parameters)
        }
        .subscribeOn(RXScheduler.concurrentBackground)
        .observeOn(RXScheduler.main)
        .subscribe(onNext: {(response) in
            print(response)
        }, onError: { (error) in
            print(error)
        }).disposed(by: rxbag)