How to Use JSON Arrays with Alamofire Parameters

Sending json array via Alamofire

You can just encode the JSON with NSJSONSerialization and then build the NSURLRequest yourself. For example, in Swift 3:

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let values = ["06786984572365", "06644857247565", "06649998782227"]

request.httpBody = try! JSONSerialization.data(withJSONObject: values)

AF.request(request) // Or `Alamofire.request(request)` in prior versions of Alamofire
.responseJSON { response in
switch response.result {
case .failure(let error):
print(error)

if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
print(responseString)
}
case .success(let responseObject):
print(responseObject)
}
}

For Swift 2, see previous revision of this answer.

post array of json with alamofire swift

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

Array put request with Alamofire

Alamofire added support for Encodable parameters in Alamofire 5, which provides support for Array parameters. Updating to that version will let you use Array parameters directly. This support should be automatic when passing Array parameters, you just need to make sure to use the version of request using encoder rather than encoding if you're customizing the encoding.



Related Topics



Leave a reply



Submit