I want to upload an image file to the backend server, using certain URL endpoint. I can easily do that using Alamofire's upload request as multipartFormData. However I want to get rid of Alamofire to minimize the dependency on third party frameworks. Here is the Alamofire code, which works:
func uploadRequestAlamofire(parameters: [String: Any], imageData: Data?, completion: @escaping(CustomError?) -> Void ) {
let url = imageUploadEndpoint!
let headers: HTTPHeaders = ["X-User-Agent": "ios",
"Accept-Language": "en",
"Accept": "application/json",
"Content-type": "multipart/form-data",
"ApiKey": KeychainService.getString(by: KeychainKey.apiKey) ?? ""]
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
if let data = imageData {
multipartFormData.append(data, withName: "file", fileName: "image.png", mimeType: "image/jpg")
}
}, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
completion(CustomError(errorCode: response.response!.statusCode))
print("Succesfully uploaded")
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
}
}
}
Here is the URLSession upload task, which doesn't work:
func requestNativeImageUpload(imageData: Data, orderExtId: String) {
var request = URLRequest(url: imageUploadEndpoint!)
request.httpMethod = "POST"
request.timeoutInterval = 10
request.allHTTPHeaderFields = [
"X-User-Agent": "ios",
"Accept-Language": "en",
"Accept": "application/json",
"Content-type": "multipart/form-data",
"ApiKey": KeychainService.getString(by: KeychainKey.apiKey) ?? ""
]
let body = OrderUpload(order_ext_id: orderExtId, file: imageData)
do {
request.httpBody = try encoder.encode(body)
} catch let error {
print(error.localizedDescription)
}
let session = URLSession.shared
session.uploadTask(with: request, from: imageData) { data, response, error in
guard let response = response as? HTTPURLResponse else { return }
print(response)
if error != nil {
print(error!.localizedDescription)
}
}.resume()
}
This is the way I call the methods for both Alamofire and URLSession:
uploadRequestAlamofire(parameters: ["order_ext_id": order_ext_id, "file": "image.jpg"], imageData: uploadImage) { [weak self] response in }
requestNativeImageUpload(imageData: uploadImage!, orderExtId: order_ext_id)
Here is what the backend server expects to receive in the request body:
let order_ext_id: String
let description: String
let file: string($binary)
This is the Codable struct to encode for request's httpBody.
struct OrderUpload: Codable {
let order_ext_id: String
let description: String
let file: String
}
Although in this demo my methods may not be fully appropriate and I don't handle the response status code, the Alamofire method works well.
Why shouldn't URLSession work ?