I have a data structure that looks like this in JSON:
[{
"value": "1",
"optionId": "be69fa23-6eca-4e1b-8c78-c01daaa43c88"
}, {
"value": "0",
"optionId": "f75da6a9-a34c-4ff6-8070-0d27792073df"
}]
Basically it is an array of dictionaries. I would prefer to use the default Alamofire methods and would not like to build the request manually. Is there a way to give Alamofire my parameters and Alamofire does the rest?
If I create everything by hand I get an error from the server that the send data would not be correct.
var parameters = [[String:AnyObject]]()
for votingOption in votingOptions{
let type = votingOption.votingHeaders.first?.type
let parameter = ["optionId":votingOption.optionID,
"value": votingOption.votingBoolValue
]
parameters.append(parameter)
}
let jsonData = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])
let json = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments)
if let url = NSURL(string:"myprivateurl"){
let request = NSMutableURLRequest(URL: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = Method.POST.rawValue
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])
AlamofireManager.Configured.request(request)
.responseJSON { response in
//Handle result
}
}
I have the same issue and resolved this way:
I created a new struct implementing the Alamofire's ParameterEncoding protocol:
struct JSONArrayEncoding: ParameterEncoding {
private let array: [Parameters]
init(array: [Parameters]) {
self.array = array
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
let data = try JSONSerialization.data(withJSONObject: array, options: [])
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
return urlRequest
}
}
Then, I can do this:
let parameters : [Parameters] = bodies.map( { $0.bodyDictionary() })
Alamofire.request(url, method: .post, encoding: JSONArrayEncoding(array: parameters), headers: headers).responseArray { ... }
It worked for me. Hope can help someone else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With