I have a simple put request and I am using Alamofire's Parameters
type to send data to the server. I would like to use codable. How do I either convert my codable struct to parameters or reconfigure the Alamofire request to take JSON objects as the parameter? What is the best and most efficient way to send post and put requests using Alamofire?
Here is what I am doing right now with Alamofire.
func addProduct(product:MainProduct, completionHandler:@escaping ((JSON?, Error?)->Void)) {
let url = "INSERT_URL"
let headers: HTTPHeaders = [
"Content-Type": "application/json"
]
var parameters:Parameters = [:]
parameters["orderId"] = product.orderId
parameters["orderSize"] = product.orderSize
parameters["theOrderStatus"] = product.orderStatus
let purchDate = Int((product.purchaseDate.timeIntervalSince1970)*1000)
parameters["purchaseDate"] = purchDate
parameters["archived"] = false
Alamofire.request(url, method:.put, parameters: parameters, encoding: JSONEncoding.default, headers:headers).responseJSON {response in
switch response.result {
case .success(let value):
print ("finish")
let swiftyJson = JSON(value)
completionHandler(swiftyJson, nil)
case .failure(let error):
completionHandler(nil, error)
}
}
}
This is our struct.
struct MainProduct:Codable{
var purchaseDate:Date
var orderId:String
var orderSize:Double
var orderStatus:OrderStatus?
var archived:Bool
private enum CodingKeys: String, CodingKey {
case purchaseDate
case orderId
case orderSize
case orderStatus = "theOrderStatus"
case archived
}
}