使用Alamofire并编码为PUT请求



我有一个简单的PUT请求,我正在使用Alamofire的Parameters类型将数据发送到服务器。我想使用Codable。如何将代码结构转换为参数,或重新配置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
    }
}

您可以制作新的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)
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新