我有一个简单的放置请求,并且正在使用Alamofire的Parameters类型将数据发送到服务器。我想使用codable。如何将我的可编码结构转换为参数,或者重新配置Alamofire请求以将JSON对象作为参数?使用Alamofire发送帖子和放置请求的最佳,最有效的方法是什么?
Parameters
这就是我现在正在使用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。试试这个代码…
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) } } }