-1

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 {


            }
        }

    }
Enzo B.
  • 2,341
  • 1
  • 11
  • 33
Deepak Verma
  • 373
  • 7
  • 19

3 Answers3

1

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)
                }
            }
    }
AtulParmar
  • 4,358
  • 1
  • 24
  • 45
0

I hope your Parameters class follows Codable protocol.

As far as I see, you are getting an error parsing that object to JSON. Hence that is the source of your error.

Could you also add code for your Parameters class / struct

Ganesh Somani
  • 2,280
  • 2
  • 28
  • 37
0

First, convert your Temp

Array into String

than pass in that in parameters of Alamofire.

extension NSArray {
    
    func toJSonString(data : NSArray) -> String {
        
        var jsonString = "";
        
        do {
            
            let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
            jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
            
        } catch {
            print(error.localizedDescription)
        }
        
        return jsonString;
    }
    
}
Community
  • 1
  • 1
Anup Gupta
  • 1,993
  • 2
  • 25
  • 40