With Swift 5 I'm trying to cut a lot of my dependencies (Alamofire), and I'm trying to understand how can I do a multipart request while using Codable and URLRequest
My code is working correctly for creating an user with a name and email, but I need to add an avatar to the struct.
After adding the avatar, how can I encode the struct in order to be a multipart request. I found some solutions online but not for scenarios like the one I'm trying to implement.
The code below is the working code for the request without an Avatar.
struct User: Codable {
let name: String
let email: String?
}
var endpointRequest = URLRequest(url: endpointUrl)
endpointRequest.httpMethod = "POST"
endpointRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
do {
endpointRequest.httpBody = try JSONEncoder().encode(data)
} catch {
onError(nil, error)
return
}
URLSession.shared.dataTask(
with: endpointRequest,
completionHandler: { (data, urlResponse, error) in
DispatchQueue.main.async {
self.processResponse(data, urlResponse, error, onSuccess: onSuccess, onError: onError)
}
}).resume()