Search code examples
iosswiftpostnsjsonserializationencodable

Post request in swift with encodable


I want to create a post request in swift but i got confused in Encodable protocols. and how to create them.

below is the data that i want to post :

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

How can i post it with Encodable or JSONSerialization?


Solution

  • This JSON is wrong. You JSON must be valid. In order to make above JSON valid we need to set array with a key.

    Wrong

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

    Correct

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

    Swift models for above JSON is this.

    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"
    

    Convert above model to json data to post. Use below code.

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