У меня есть следующий код, который используется в моем текущем проекте для загрузки изображения на сервер, используя данные многоэлементной формы, как и в случае с обычными параметрами.
// Create function which accept Parameters and UIImage type
// Completion block with return [String: Any] or Error
func addProfileDetails(parameters: Parameters, image: UIImage?, completion: @escaping (ProfileImageModel?, Error?) -> Void) {
// If image not nil then code with parameters and image
if image != nil {
Alamofire.upload( multipartFormData: { multipartFormData in
for (key, value) in parameters {
if let data = (value as! String).data(using: .utf8) {
multipartFormData.append(data, withName: key)
}
}
let imageData = image?.jpegData(compressionQuality: 0.5)
multipartFormData.append(imageData!, withName: "profile_image", fileName: "profileImage", mimeType: "image/jpeg")
}, to: YourUrl, headers: YourHeaders, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response(completionHandler: { (defaultDataResponse) in
guard let httpResponse = defaultDataResponse.response else {
completion(nil, defaultDataResponse.error)
return
}
if httpResponse.statusCode == 200 {
do {
// Decode json to my model
let genericModel = try JSONDecoder().decode(ProfileImageModel.self, from: defaultDataResponse.data!)
completion(genericModel, nil)
} catch {
completion(nil, error)
}
} else {
completion(nil, defaultDataResponse.error)
}
})
case .failure(let encodingError):
completion(nil, encodingError)
}
})
} else {
// Get you url
let baseUrl = YourUrlString
// Setup normal parameters
// This is mine, you can use yours
let dataString = "first_name=\(parameters["first_name"]!)&last_name=\(parameters["last_name"]!)&bio=\(parameters["bio"]!)&image_status=\(parameters["image_status"]!)&location=\(parameters["location"]!)&latitude=\(parameters["latitude"]!)&longitude=\(parameters["longitude"]!)"
let url = URL(string: baseUrl)! // Create url
let session = URLSession.shared // Create shared session instance
var request = URLRequest(url: url) // Create url request
request.httpMethod = "POST" // Set http method as POST
// Encode parameters using utf8
if let encodedData = dataString.data(using: .utf8) {
request.httpBody = encodedData
}
// Set content type and encoding acceptance parameters in header
request.addValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("gzip", forHTTPHeaderField: "Accept-Encoding")
request.addValue("ios", forHTTPHeaderField: "requestfrom")
if let authToken = UserDefaults.UserData.string(forKey: .authToken) {
request.addValue(authToken, forHTTPHeaderField: "authtoken")
}
// Create Session Task
let task = session.dataTask(with: request, completionHandler: { data, response, error in
// Hide progress
DispatchQueue.main.async {
AppDelegate.shared.showProgress(showHUD: .hide, message: "")
}
// Check error is nil
guard error == nil else {
completion(nil, error)
return
}
// Check data not empty
guard let data = data else {
completion(nil, nil)
return
}
do {
// Decode JSON to my ProfileImageModel model, you can use [String: Any] or model
let genericModel = try JSONDecoder().decode(ProfileImageModel.self, from: data)
completion(genericModel, nil)
} catch {
completion(nil, error)
}
})
task.resume()
}
}
Надеюсь, это поможет вам.