Вот рабочий код из моей работы. Вам нужно будет импортировать некоторые необходимые классы и изменить параметры в зависимости от параметров вашего веб-сервиса.
func uploadImage(url:String, parameters:Dictionary<String, Any>, images:[UIImage]) {
let URL = url
//print (URL, parameters)
//show uploading
SVProgressHUD.show(withStatus: NSLocalizedString("Uploading Image", comment: "").loadigSuffix())
SVProgressHUD.setDefaultMaskType(.none)
Alamofire.upload(multipartFormData: { multipartFormData in
for image_ in images {
if let imageData = self.serverCompatibleImageData(image: image_) {
//print("final Image size = ", imageData)
multipartFormData.append((imageData), withName: "userfile[]", fileName: "file.jpg", mimeType: "image/jpg")
}
}
for (key, value) in parameters {
let val = String(describing: value)
multipartFormData.append((val.data(using: .utf8))!, withName: key)
}
}, to: URL, method: .post, headers: ["Authorization" : "auth_token"],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard self != nil else {
debugPrint("Self does not have the authority here!")
return
}
var serializedData : Any? = nil
var message = NSLocalizedString("Success", comment: "")+"!"//MUST BE CHANGED TO RELEVANT RESPONSES
var success:Bool!
//check content availability and produce serializable response
do {
serializedData = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments)
//debugPrint(message, "Response Dictionary:", serializedData ?? "Data could not be serialized", separator: "\n")
success = true
}catch{
message = NSLocalizedString("Webservice Response error", comment: "")+"!"
let string = String.init(data: response.data!, encoding: .utf8) as String!
success = false
do {
if let s = string?.substring(from: (string?.index(of: "{")!)!) {
if let data = s.data(using: String.Encoding.utf8) {
serializedData = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
debugPrint(message, "_:", serializedData ?? "Data could not be serialized", separator: "\n")
}
}
}catch{
debugPrint(message, error.localizedDescription, "Respone String:", string ?? "No respone value.", separator: "\n")
}
}
//call finised response in all cases
self?.delegate?.uploaded?(succes: success, and: serializedData, message: message)
}
case .failure(let encodingError):
debugPrint("Error:\(encodingError)")
//self.handleImageError()
}
})
}