Using Alamofire and Codable for put request

11,219

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)
        }
    }
}
Share:
11,219
Nevin Jethmalani
Author by

Nevin Jethmalani

I'm passionate about beautiful UX, finding the most efficient solution to problems and dreaming of ways to make the world simpler. Interested in fashion, Swift, iOS, blockchain, and cryptocurrency.

Updated on June 15, 2022

Comments

  • Nevin Jethmalani
    Nevin Jethmalani about 2 years

    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
        }
    }