Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Alamofire and Codable for put request

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
    }
}
like image 662
Nevin Jethmalani Avatar asked Dec 06 '17 23:12

Nevin Jethmalani


1 Answers

You can make a new URLRequest and set httpBody to your encoded jsonData. Try this code...

func addProduct(product: MainProduct, completionHandler: @escaping ((JSON?, Error?)->Void)) {

    let encoder = JSONEncoder()
    let jsonData = try! encoder.encode(product)

    let url = "INSERT_URL"

    var request = URLRequest(url: url)
    request.httpMethod = HTTPMethod.put.rawValue
    request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
    request.httpBody = jsonData

    Alamofire.request(request).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)
        }
    }
}
like image 178
Daniel Avatar answered Feb 20 '23 04:02

Daniel