Using Alamofire and Codable for put request

前端 未结 1 1502
心在旅途
心在旅途 2020-12-17 00:09

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 coda

相关标签:
1条回答
  • 2020-12-17 00:47

    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)
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题