Post swift 请求可编码

Post request in swift with encodable

我想在 swift 中创建一个 post 请求,但我对 Encodable 协议感到困惑。以及如何创建它们。

下面是我想要的数据 post :

{
answers: [{
            "time": 1,
            "score": 20,
            "status": true,
            "answer": 456
 }],
challenge_date": "2019-03-13"  
}

我如何post它与EncodableJSONSerialization

使用 Alamofire 并使用 encoding: JSONEncoding.default 将参数作为字典传递,请参见以下代码。

    Alamofire.request(urlString!, method: .post, parameters: parameter, encoding: JSONEncoding.default, headers: headers)
        .responseJSON { (response) in
            switch response.result {
            case .success:
                print(response)                    
            case .failure(let error):
                print(error.localizedDescription)
            }
    }

这个JSON是错误的。您 JSON 必须有效。为了使上面的 JSON 有效,我们需要用一个键设置数组。

错误

{
 [{
            "time": 1,
            "score": 20,
            "status": true,
            "answer": 456
 }],
challenge_date": "2019-03-13"  
}

正确

{
    "array": [{
                "time": 1,
                "score": 20,
                "status": true,
                "answer": 456
     }],
    "challenge_date": "2019-03-13"  
}

Swift以上型号JSON是这个

struct YourJSONModel: Codable {
    var challenge_date: String
    var array: Array<ResultModel>
}
struct ResultModel: Codable {
    var time: Int
    var score: Int
    var status: Bool
    var answer: Int
}

var result = ResultModel()
result.time = 10
result.score = 30
result.status = true
result.answer = 250


var jsonModel = YourJSONModel()
jsonModel.array = [result]
jsonModel.challenge_date = "2019-03-13"

将上述模型转换为 json 数据为 post。使用下面的代码。

let jsonData = try! JSONEncoder().encode(jsonModel)

var request = URLRequest(url: yourApiUrl)
request.httpBody = jsonData
request.httpMethod = "POST"

Alamofire.request(request).responseJSON { (response) in
            switch response.result {
            case .success:
                print(response)                    
            case .failure(let error):
                print(error.localizedDescription)
            }
}