0

I am trying to execute this method that I did on android where with the help of retrofit with the @Body clause I can send data in the service body, as it is appreciated I do not need to use key - value, I only use @Body and the service works perfectly.

@POST("/Rest/Login") // <== post
Call<Car> getLogin(@Body Car car); //// **<=== @BODY**

but Now I try to do the same in swift using the JSONEncoding.default but I don't know how to add my complete class to send in the service since the only way to send is with a key value in a Parameters variable. Alamofire's documentation indicates the same by providing this example which does not work for me.

let parameters: Parameters = [
    "foo": [1,2,3],
    "bar": [
        "baz": "qux"
    ]
]

Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default)

Because the service I run does not have a key-value, only the model is sent in the body and that's it. As the example I provide on android using @Body

dbenitobaldeon
  • 324
  • 3
  • 20
  • Off of the top of my head, I think it’s JSONEncoding().encode(YourCodableClassOrStructName.self) – Jake Aug 10 '19 at 20:28
  • I do not understand ? where would that go @Jake – dbenitobaldeon Aug 10 '19 at 20:31
  • That should create a dictionary like Parameters that you feed to alamofire – Jake Aug 10 '19 at 20:33
  • So if you have a class of `Car: Codable` and it has year, make, model, and serviceRecords. You’ll get the appropriate Json you’d need for the request body by using that function – Jake Aug 10 '19 at 20:36
  • And how will I send it in the service? since the variables of the parameters type are key - value..!! Alamofire.request(Constants.ADD_ADDRESS, method: .post, parameters: <#T##Parameters?#>) @Jake – dbenitobaldeon Aug 10 '19 at 20:37
  • And how will I send it in the service? since the variables of the parameters type are key - value..!! Alamofire.request(Constants.ADD_ADDRESS, method: .post, parameters: <#T##Parameters?#>) @Jake – dbenitobaldeon Aug 10 '19 at 21:09
  • Cast it ‘as Parameters’ – Jake Aug 10 '19 at 21:14
  • i can't cast it ! @Jake – dbenitobaldeon Aug 10 '19 at 21:25
  • Address' is not convertible to 'Parameters' (aka 'Dictionary') – dbenitobaldeon Aug 10 '19 at 21:25
  • If your service accepts key/value POST data rather than JSON then you will need to write some code to put the various properties of your object into a dictionary to send. There is no in-built "convert an object to a dictionary representation" function. – Paulw11 Aug 10 '19 at 22:30
  • Sorry I missed a step. After you encode, you get data. If you want a dictionary you need to use JSONSerialization to take the data and turn it into a dictionary – Jake Aug 10 '19 at 23:56

0 Answers0