Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

json - Using Alamofire and Codable for put request

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
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...