Search code examples
iosarraysjsonswiftalamofire

post array of json with alamofire swift


How can i post array of json objects with alamofire in swift?

my final data (which i want to post) looks like:

temp = [{
        "time": 1,
        "score": 20,
        "status": true,
        "answer": 456
    },
    {
        "time": 0,
        "score": 0,
        "status": false,
        "answer": 234
    },
    {
        "time": 0,
        "score": 20,
        "status": true,
        "answer": 123
    }
]

i got hint that i have to create custom parameter encoding but i am confused how can i do that. Someone please help me.

my current code looks like
let parameters: Parameters = [
    "answers": temp,
    "challenge_date": "2019-03-01"
]

Alamofire.request("...url", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
    .responseJSON {
        response in

            if
        let status = response.response ? .statusCode {
            let classFinal: JSON = JSON(response.result.value!)

            if (status > 199 && status < 300) {
                self.dismiss(animated: true)
            } else {


            }
        }

    }

Solution

  • In your code change method .put to .post, and not required to SVProgressHUD.dismiss() in else, because you already dismiss before if else part

    Also, you need to convert your JSON string(temp variable) to array and then pass with the parameter.

    let parameters: Parameters = [
                "answers": temp,
                "challenge_date": "2019-03-01"
            ]
    
        Alamofire.request("...url", method: .post, parameters: parameters, encoding:  JSONEncoding.default , headers: headers)
            .responseJSON { response in
    
                if let status = response.response?.statusCode {
                let classFinal : JSON = JSON(response.result.value!)
                    SVProgressHUD.dismiss()
                    if status > 199 && status < 300 {                    
                         self.dismiss(animated: true)
                    }
                }
        }