使用Alamofire和Codable进行请求

时间:2017-12-06 23:32:38

标签: json swift swift4 codable

我有一个简单的put请求,我正在使用Alamofire的Parameters类型将数据发送到服务器。我想用可编码的。如何将我的可编码结构转换为参数或重新配置Alamofire请求以将JSON对象作为参数?使用Alamofire发送和发送请求的最佳和最有效的方法是什么?

以下是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)
        }
    }
}

这是我们的结构。

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

1 个答案:

答案 0 :(得分:13)

您可以制作新的URLRequest并将httpBody设置为已编码的jsonData。试试这段代码......

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