Multiple file upload with array of parameters using Alamofire

╄→гoц情女王★ 提交于 2019-12-01 13:59:04

You can upload each image and its param in an Operation. Your Operation should look something like this:

class UploadImageOperation: Operation {
private var image: UIImage

init(withImage: UIImage) {
    super.init()

    image = withImage
}

override func main() {
    let imgData = UIImageJPEGRepresentation(image, 0.2)!
    Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")

        for (key, value) in params {
            multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        }
    },
                     to:URLUpdateProfile,
                     method:.post,
                     headers:headers)
    { (result) in
        switch result {
            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (progress) in
                    print("Upload Progress: \(progress.fractionCompleted)")
                })

                upload.responseJSON { response in
                    print(response.result.value)
                }

            case .failure(let encodingError):
                print(encodingError)  
            }
        }
    }
}

Then you create the operations and add them to the queue like this:

let opQueue = OperationQueue()
opQueue.name = "imageUploadQueue"
opQueue.maxConcurrentOperationCount = 5 //number of images you want to be uploaded simultaneously
opQueue.qualityOfService = .background

for image in arrayOfImages {
    let uploadImageOperation = UploadImageOperation(withImage: image)
    opQueue.addOperation(uploadImageOperation)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!