Reputation: 182
I would like to know how I can put a SwiftyJSON array into my parameters for the Alamofire request.
Actually I use this code (Swift 3) to setup the parameters for the request:
let params = ["customObjects": customObjects.map({$0.toJSON()})]
...but this fires an exception if I try to start the request:
uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'
The "customObjects" are an array of my custom model class.
If you need any more information let me know.
Upvotes: 1
Views: 1118
Reputation: 3918
You can convert a SwiftyJSON object (called yourJSON
here) to parameters like so:
let parameters : Parameters = yourJSON.dictionaryObject ?? [:]
Then you can use it in an Alamofire request like so:
Alamofire.request("https://yourURL.com/somePath", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
// ... do whatever you would like with the response
}
Upvotes: 2
Reputation: 182
I found the solution by myself:
let params = ["customObjects": customObjects.map({$0.toDictionary()})]
And here the toDictionary() func inside my CustomObject:
func toDictionary() -> [String: Any] {
let dict: [String: Any] = [
"exampleKey": "exampleValue",
"exampleKey2": "exampleValue2"
]
return dict
}
I guess this is because you can setup Alamofire with encoding: JSONEncoding.default
.
Upvotes: 0